
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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 Articles
- Count occurrence of all elements of list in a tuple in Python
- Count frequencies of all elements in array in Python\n
- Python – Rows with all List elements
- Find missing elements in List in Python
- Count Elements x and x+1 Present in List in Python
- 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 frequencies of all elements in array in Python using collections module
- Python - Check if all elements in a List are same
- Python - Check if all elements in a list are identical
- Find sum of elements in list in Python program
- Find common elements in list of lists in Python
- Program to find a list of product of all elements except the current index in Python
- Python program to find sum of elements in list
