Find all elements count in list in Python


Many times we need to count the elements present in a list for some data processing. But there may be cases of nested lists and counting may not be straight forward. In this article we will see how to handle these complexities of counting number of elements in a list.

With For loop

In this approach we use two for loops to go through the nesting structure of list. In the below program we have nested list where inner elements have different number of elements inside them. We also apply the len() function to calculate the length of the flattened list.

Example

 Live Demo

listA = [[2,9, 6], [5, 'a'], [0], [12,'c', 9, 3]]

# Given list
print("Given list : ",listA)

res = len([x for y in listA for x in y])

# print result
print("Total count of elements : " ,res)

Output

Running the above code gives us the following result −

Given list : [[2, 9, 6], [5, 'a'], [0], [12, 'c', 9, 3]]
Total count of elements : 10

With Chain

In this approach we apply the chain method which brings out all the inner elements from the list by flattening them and then convert it to a list. Finally apply the len() function so that the count of the elements in the list found.

Example

from itertools import chain
listA = [[2,9, 6], [5, 'a'], [0], [12,'c', 9, 3]]

# Given list
print("Given list : ",listA)

res = len(list(chain(*listA)))

# print result
print("Total count of elements : " ,res)

Output

Running the above code gives us the following result −

Given list : [[2, 9, 6], [5, 'a'], [0], [12, 'c', 9, 3]]
Total count of elements : 10

Updated on: 26-Aug-2020

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements