Count Elements Using List Comprehension in Python (2 Examples)
In this tutorial, you’ll learn how to count elements in a list in the Python programming language using list comprehension.
The content of the tutorial looks as follows:
Let’s dive into the examples.
Creation of Example Data
my_list = [5, 35, 82, 64, 29, 37, 98, 75, 13, 57]
Now, let’s see different ways of counting the elements of my_list using list comprehension in the next examples.
Example 1: Count Odds in List Using List Comprehension
In this example, we will use the list comprehension method to return the number of odd numbers in our list via iterating through the elements of the list and keeping the numbers which cannot be divided by 2. Regarding condition is set by the if statement
num % 2 != 0.
odds = [num for num in my_list if num % 2 != 0] print(odds) # [5, 35, 29, 37, 75, 13, 57]
The output above shows the new list created which contains the odd numbers in my_list.
Example 2: Count Elements in List Smaller Than Arbitrary Number Using List Comprehension
The list comprehension method can also be used to count the numerical elements smaller than an arbitrary number. For instance, we can count the elements that are smaller than 20 in our list. See how the list comprehension is conditioned to be smaller than 20 below.
smallthan = len([elem for elem in my_list if elem < 20]) print(smallthan) # 2
As shown, there are two numbers in our list smaller than 20. The conditions that can be set are not limited by the given examples, yet they are out of the scope of this tutorial.
Video, Further Resources & Summary
Do you need more explanations on how to count elements in a list in Python? Then you should look at the following YouTube video of the Statistics Globe YouTube channel.
The YouTube video will be added soon.
Moreover, you could check some of the other tutorials on Statistics Globe:
- Count Duplicates in List in Python
- Convert List from Character String to Integer in Python
- Access List Element by Index in Python
- Learn Python
This post has shown examples of how to count in a list in Python using list comprehension. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Paula Villasante Soriano. Please have a look at Paula’s author page to get more information about her academic background and the other articles she has written for Statistics Globe.
Statistics Globe Newsletter