

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Questions & Answers
- Count occurrence of all elements of list in a tuple in Python
- Count frequencies of all elements in array in Python
- Find missing elements in List in Python
- Python – Rows with all List elements
- Check if list contains all unique elements in Python
- List consisting of all the alternate elements in Python
- Python Program to Find Number of Occurrences of All Elements in a Linked List
- Count Elements x and x+1 Present in List in Python
- Find sum of elements in list in Python program
- Find common elements in list of lists in Python
- Python - Check if all elements in a List are same
- Python - Check if all elements in a list are identical
- Count frequencies of all elements in array in Python using collections module
- Python program to find sum of elements in list
- Find elements of a list by indices in Python