- Python: Get Number of Elements in a List
- Built-in Function len()
- Using a for Loop
- Get Number of Unique Elements in a List
- List of Lists using len()
- Free eBook: Git Essentials
- Get Total Number of Elements in a List Containing Other Lists
- Nested Lists
- Conclusion
- Python Count Number Of Elements In List – Full Guide
- Using Len() Function
- Using For Loop
- Count Number of Elements In List Matching Criteria
- Count None In List
- Conclusion
- You May Also Like
Python: Get Number of Elements in a List
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 contain a combination of types, like 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 manually count the elements in list_a we get 5 elements overall. If we do the same for list_b we will see that we have 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 top-level unique elements.
Built-in Function len()
The most straightforward and common way to get the number of elements in a list is to use the Python built-in function len() .
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)
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. This method does not count the lengths of any lists within the list, only top-level elements.
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 another 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 set :
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 of this article, 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 can come in handy.
Get Total 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))
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 the number of 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
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, [89], 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, [89], 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, [89], 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.
Conclusion
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.
Python Count Number Of Elements In List – Full Guide
Python lists are built-in datatype used to store multiple items in a single variable or in other words a collection of data.
You can count the number of elements in a list in python using the len(list) function.
This tutorial teaches you the different methods to count the number of elements in a list.
If you’re in Hurry
You can use the below code snippet to get the number of items in the List.
You’ll see the output 3 as the list contains 3 items.
If You Want to Understand Details, Read on…
In this tutorial, you’ll learn the different methods and use cases to count the number of items available in the list.
Using Len() Function
You can find the length of the list using the len() function.
There are 3 elements in the list.
You’ll see the output as 3 .
You’ve calculated the items in the list which have the same type of values.
This is how you can get the number of elements in the list using the len() function.
Using For Loop
In this section, you’ll learn how to count the number of elements in a list using the for loop.
for loop is used to iterate over a sequence of values.
To get the number of elements in the list,
- Iterate over the list and increment the counter variable during each iteration.
- Once the iteration is over, you’ll return the count variable, which has the total number of elements in the list.
- A list is initialized with different types of values
- Created a function which will iterate the list and count the elements
- Printed the count using a print statement.
list = ['a',1, True, None] def get_no_of_elements(list): count = 0 for element in list: count += 1 return count print("Number of elements in the list: ", get_no_of_elements(list))
There are 4 elements in the list including the None value. Hence you’ll see output 4 .
Number of elements in the list: 4
This is how you can get the number of elements in a list using for loop.
Count Number of Elements In List Matching Criteria
In this section, you’ll learn how to count the number of elements in a list that is matching criteria or a within a specified condition.
- First, create a function that will check if an item matches the condition.
- For example, if the number is greater than 10. The function will return True if the condition is passed. Else it’ll return False .
- Execute the function for each item in the list using the list comprehension.
- Finally, you can sum the results where the condition is True .
# Define any condition here def condition(x): return x > 10 # Create the list list = [10, 15, 25, 28, 3, 5, 8] # Count the number of matching elements print(sum(condition(x) for x in list))
The sample list has 3 items that are greater than 10. Hence you’ll see output 3 .
This is how you can get the number of items in the list matching criteria.
Count None In List
In this section, you’ll learn how to count None in list.
You can count None in a list using the list comprehension method.
In list comprehension, you’ll iterate through the list and sum the None value.
list = ['one','two', 'three', None, None,'Six', None, 'Eight'] print("Number of None is List : ", sum(x is None for x in list))
Number of None is List : 3
This is how you can count None in the List.
Conclusion
To summarize, you’ve learned how to get the number of elements in the list. You’ve used the len() function and for loops to count the number of elements in the list. You’ve also learned how to find list length.
If you have any questions, comment below.