How to Count Elements in List Python

Vaibhhav Khetarpal Feb 02, 2024
  1. Use the len() Function to Count the Number of Elements in the List in Python
  2. Use the for Loop to Count the Number of Elements in the List in Python
How to Count Elements in List Python

The list is a built-in datatype provided in Python. It stores multiple items under a single variable. The use of Lists is very common in Python Programming. Lists in Python can be nested.

This tutorial will discuss different methods to count the number of elements in a List in Python.

Use the len() Function to Count the Number of Elements in the List in Python

Lists in Python can store multiple elements of different data types.

The built-in len() function in Python returns the total number of items in a list, without any regard to the type of elements it contains.

We can also use the len() function to count the number of elements of the other three built-in Datatypes that Python offers, namely Tuple, Set, and Dictionary.

The following code uses the len() function to get the number of elements in the list.

list1 = ["God", "Belief", 10, 31, "Human"]

print("The total number of elements in the list: ", len(list1))

Output:

The total number of elements in the list:  5

Use the for Loop to Count the Number of Elements in the List in Python

Another basic way to count the number of elements is to make use of the for loop. The loop begins with the count set to 0 and proceeds until the last element; the count is incremented by one whenever an element in the list is encountered in the loop iteration.

The following code uses the for loop to get the number of elements in the list.

list2 = ["Hey", 20, 14, "Look", "An Example List"]


def total_elements(list):
    count = 0
    for element in list:
        count += 1
    return count


print("The total number of elements in the list: ", total_elements(list2))

Output:

The total number of elements in the list:  5
Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn

Related Article - Python List