Problem Formulation: Given a list of elements in Python. How to get the number of elements in the list?

Examples:
List | Number of Elements |
---|---|
[3, 42, 2] | 3 |
[] | 0 |
['Alice', 'Bob', 'Carl'] | 3 |
[(1, 2), [3, 4]] | 2 |
Method 1: len()
The most Pythonic way to get the number of list elements is Python’s built-in function len()
that returns the length of the list, regardless of its elements’ types.
>>> len([]) 0 >>> len([3, 42, 2]) 3 >>> len(['Alice', 'Bob', 'Carl']) 3 >>> len([(1, 2), [3, 4]]) 2
You can dive into Python’s built-in len()
function in more detail in my video tutorial:
You can also use the len()
function to determine the number of elements in a Python list, tuple, string, dictionary, and set.
Related Tutorial: Python len()
Method 2: len() + set() to Count the Number of Unique Elements
To count the number of unique list elements, you can combine Python’s built-in functions len()
and set()
to obtain len(set(list))
. This converts the list to a set and removes all duplicates. The length of the duplicate-free set is the number of unique elements in the original list.
Here’s an example:
>>> lst = [1, 2, 3, 1, 1, 1] >>> len(lst) 6 >>> len(set(lst)) 3
Method 3: How to Get the Number of Elements in a Nested List?
A nested list is a list that contains other lists that may can contain other lists and so on. To get the number of elements in a nested list, you can flatten the list and pass the flattened list into the len() function.
Here’s the code:
>>> from pandas.core.common import flatten >>> lst = [[1, 2], [3, [4, 5, 6]], [4]] >>> list(flatten(lst)) [1, 2, 3, 4, 5, 6, 4] >>> len(list(flatten(lst))) 7
Note that there are many more ways to flatten a list of lists. You can read about them in our full tutorial.
Related Tutorial: Flatten A List Of Lists In Python