In Python, to count the items in a list which match a certain criterion, you can use comprehension and the Python sum() function.

lst = [5, 6, 2, 9, -1, 3]

count_gt_4 = sum(x > 4 for x in lst)

print(count_gt_4)

#Output:
3

You can also use an if statement to count items in a list matching a certain criterion with comprehension as shown below.

lst = [5, 6, 2, 9, -1, 3]

count_gt_4 = len([x for x in lst if x > 4])

print(count_gt_4)

#Output:
3

When working with collections of data in Python, the ability to easily get statistics and additional information about your data is very valuable.

One such piece of information when working with lists in Python is the count of items which match a given criteria.

With comprehension, we can easily get the items matching given criteria and then use the Python sum() function to get the count of the list.

Below is an example showing how you can get the count of items in a list matching criteria with Python. Comprehension here returns a list of boolean values and sum() sums up the number of ‘True’ items.

lst = [5, 6, 2, 9, -1, 3]

count_gt_4 = sum(x > 4 for x in lst)

print(count_gt_4)

#Output:
3

Using List Comprehension to Get Count of Items Matching Criteria in Python

If you have conditions which are a little more complex or have slightly different requirements, you can use comprehension with the len() function to get the count of items matching a particular criteria.

In this example, you first build the list and then find the length of the filtered list.

Depending on your code, this may be better than the previous example.

Below is an example of how you can use an if statement with list comprehension to filter a list in Python, and then get the length of that list.

lst = [5, 6, 2, 9, -1, 3]

filtered_lst = [x for x in lst if x > 4]

count_gt_4 = len(filtered_lst)

print(filtered_lst)
print(count_gt_4)

#Output:
[5, 6, 9]
3

This can be useful if you want to use the filtered list later in your code.

Hopefully this article has been useful for you to learn how to count the number of items in a list which match criteria in Python.

Categorized in:

Python,

Last Update: March 14, 2024

Tagged in: