Getting the number of elements in a list in Python is a common operation. For example, you will need to know how many elements the list has whenever you iterate through it. Remember that lists can have a combination of integers, floats, strings, booleans, other lists, etc. as their elements:
# List of just integers list_a = [12, 5, 91, 18] # List of integers, floats, strings, booleans list_b = [4, 1.2, "hello world", True]
If we count the elements in
list_a we get 5 elements overall. If we do the same for
list_b we will get 4 elements.
There are different ways to get the number of elements in a list. The approaches vary whether you want to count nested lists as one element or all the elements in the nested lists, or whether you're only interested in unique elements, and similar.
Built-in Function len()
The most straightforward way to get the number of elements in a list is to use the Python built-in function
Let's look at the following example:
list_a = ["Hello", 2, 15, "World", 34] number_of_elements = len(list_a) print("Number of elements in the list: ", number_of_elements)
Which prints out:
Number of elements in the list: 5
As the name function suggests,
len() returns the length of the list, regardless of the types of elements in it.
Using a for Loop
Another way we can do this is to create a function that loops through the list using a
for loop. We first initialize the count of the elements to 0 and every time a loop iteration is performed, the count increases by 1.
The loop ends when it iterates over all the elements, therefore the count will represent the total number of elements in the list:
list_c = [20, 8.9, "Hi", 0, "word", "name"] def get_number_of_elements(list): count = 0 for element in list: count += 1 return count print("Number of elements in the list: ", get_number_of_elements(list_c))
Running this code will print:
Number of elements in the list: 6
This is a much more verbose solution compared to the
len() function, but it is worth going through it as we will see later in the article that the same idea can be applied when we're dealing with a list of lists. Additionally, you might want to perform some operation either on the elements themselves or an operation in general, which is possible here.
Get Number of Unique Elements in a List
Lists can have multiple elements, including duplicates. If we want to get the number of elements without duplicates (unique elements) we can use another built-in function
set(). This function creates a
set object, which rejects all duplicate values.
We then pass that into the
len() function to get the number of elements in the
list_d = [100, 3, 100, "c", 100, 7.9, "c", 15] number_of_elements = len(list_d) number_of_unique_elements = len(set(list_d)) print("Number of elements in the list: ", number_of_elements) print("Number of unique elements in the list: ", number_of_unique_elements)
Number of elements in the list: 8 Number of unique elements in the list: 5
We can see that
list_d has a total of 8 elements, among which 5 are unique.
List of Lists using len()
In the introduction, we saw that elements of lists can be of different data types. However, lists can have, in turn, lists as their elements. For example:
list_e = [[90, 4, 12, 2], , [34, 45, 2], [9,4], "char", [7, 3, 19]]
If we use the built-in function
len(), the lists count as single elements, so we will have:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
number_of_elements = len(list_e) print("Number of elements in the list of lists: ", number_of_elements)
Number of elements in the list of lists: 6
Note that the empty list counts as one element. If a list within a list contains more than one element, they aren't taken into consideration. This is where a
for loop comes in handy.
Get Number of Elements in a List Containing Other Lists
If we want to count all the elements inside a list containing other lists, we can use a
for loop. We can initialize the
count variable to 0 and loop through the list. In every loop iteration,
count increases by the length of that list.
We will use the built-in function
len() to get the length:
list_e = [[90, 4, 12, 2], , [34, 45, 2], [9,4], "char", [7, 3, 19]] def get_all_elements_in_list_of_lists(list): count = 0 for element in list_e: count += len(element) return count print("Total number of elements in the list of lists: ", get_all_elements_in_list_of_lists(list_e))
The output is:
Total number of elements in the list of lists: 16
There are a few important things to note in this example. Firstly, this time the empty list did not affect the total count. This is because in every loop we consider the length of the current nested list, and since the length of an empty list is 0,
count is increased by 0.
However, you can see that every character of the string
"char" counts towards the total number of elements. This is because the
len() function acts on the string by returning all its characters. We can avoid this situation by using the same approach as in the section below, which would also allow us to have elements other than lists.
Another fun way of doing the same thing as in the previous example is by using list comprehension:
number_of_elements = sum([len(element) for element in list_e])
This line essentially does two things. First, it creates a new list containing the lengths of all the elements of the original list. In our case that would be
[4, 0, 3, 2, 4, 3]. Secondly, it calls the
sum() function using the newly generated list as a parameter, which returns the total sum of all the elements, giving us the desired result.
Nested lists are lists that are elements of other lists. There can be multiple levels of lists inside one another:
list_f = [30, 0.9, [8, 56, 22, ["a", "b"]], [200, 3, [5, , 10]]]
We can see that
["a", "b"] is contained in the list
[8, 56, 22, ["a", "b"]], which, in turn, is contained in the main list
[30, 0.9,[200, 3, [5, , 10]]].
Again, we initialize the
count variable to 0. If we want to get the overall number of elements in the nested list, we first need to check if the element is a list or not. If it is, we loop inside the list and recursively call the function until there are no nested lists left. All the elements other than lists (integers, strings, etc.) will increase the count by 1.
Note that this is also the solution to the problems caused by the previous approach.
Let's take a look at the code for counting elements in nested lists:
list_f = [30, 0.9, [8, 56, 22, ["a", "hello"]], [200, 3, [5, , 10]]] def get_elements_of_nested_list(element): count = 0 if isinstance(element, list): for each_element in element: count += get_elements_of_nested_list(each_element) else: count += 1 return count print("Total number of elements in the nested list: ", get_elements_of_nested_list(list_f))
Running this code would give us:
Total number of elements in the nested list: 12
Note that we used the built-in function
isinstance() that checks if the first argument is an instance of the class given as the second argument. In the function above, it checks if the element is a list.
The first element
30 is an integer, so the function jumps to the
else block and increases the count by 1. When we get to
[8, 56, 22, ["a", "hello"]], the function recognizes a list, and recursively goes through it to check for other lists.
We saw that according to the type of list we have, there are different ways to get the number of elements.
len() is definitely the quickest and simplest function if we have flat lists.
With lists of lists and nested lists,
len() will not count the elements inside the lists. In order to do that, we need to loop through the whole list.