Problem Formulation: Given a list of elements in Python. How to get the number of elements in the list?
|List||Number of Elements|
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:
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
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]], ] >>> 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
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.