In this article, we will discuss different ways to get the number of elements in a list or a list of lists or a nested list in Python.
Table Of Contents
Get number of elements in a simple list
We can use the len() function to get the count of elements in a list. For example,
listOfNumbers = [11, 12, 13, 14, 15, 34, 67, 22] # Get Number of elements in a list num = len(listOfNumbers) print(num)
Output:
8
The len() function accepts a sequence as an argument and calls its __len__() function. In case of a list, the __len__() function will return the count of number of elements in the list. So, instead of using len(), we can also call the__len__() function to get the number of elements in a list.
For example,
Frequently Asked:
listOfNumbers = [11, 12, 13, 14, 15, 34, 67, 22] # Get Number of elements in a list num = listOfNumbers.__len__() print(num)
Output:
8
Get number of elements in a list of lists
In case of a list of lists, iterate over all the sub lists one by one and aggregate the count of elements in each sublist. For example,
listOfLists = [ [11, 12, 13, 14, 15], [22, 23, 24, 25, 26], [42, 43, 44, 45, 46]] num = 0 # Get Number of elements in a list of lists for seq in listOfLists: num += len(seq) print(num)
Output:
15
Get number of elements in a nested list
A nested list is a kind of list that might contain,
Latest Python - Video Tutorial
- Individual elements
- Another lists
- Another list of lists
- Another nested lists
Now to get the number of elements in a nested list, we need to use the reccursion. We will create a function to get the count of elements in nested list. Inside that function, we will iterate over each element of the list and if any element is of list type, then we call the same function with that objet to get the count of elements in that. This reccursive function will exit when all elements of list are covered.
For example,
nestedList = [ 11, [34, 55], 12, [34, 44], [ [11, 12], 13, [234, 55, 5], 15, 3], [22, [22, [22]]]] def getLen(listObj): num = 0 for elem in listObj: if isinstance(elem, list): num += getLen(elem) else: num += 1 return num # get number of elements in a nested list num = getLen(nestedList) print(num)
Output:
17
Summary
We learned different ways to get the number of items in a list in Python. Also, we discussed how to get the count of individual elements in a list of lists or a nested list in Python. Happy Coding.
Latest Video Tutorials