How do I count items in a list based on a condition in Python.
There are many ways to count the occurrences of items in a list based on a condition. Here you will see two of them: one example with map and one example by using list comprehension.
Start by creating a list of names. Note that chuck appears twice in the list.
>>> names = ["vera", "chuck", "dave", "chuck"] >>> names ['vera', 'chuck', 'dave', 'chuck']
Count occurrences by using Map
By using map you can provide a lambda with the condition like this:
>>> map(lambda x: x == "chuck", names) <map object at 0x102f4dc18>
This results in a map object that we can inspect by converting it to a list:
>>> list(map(lambda x: x == "chuck", names)) [False, True, False, True]
You see that the map has converted the values in the list
names to boolean values. If you replace list with sum, Python will calculate the total of
>>> sum(map(lambda x: x == "chuck", names)) 2
Count occurrences by using List comprehension
List comprehension is another way to map lists to create new lists. You can start by using a list comprehension that does not filter the list at all and thus returns a copy of the original list:
>>> [n for n in names] ['vera', 'chuck', 'dave', 'chuck']
To filter that list, you can use
>>> [n for n in names if n == "chuck"] ['chuck', 'chuck']
Now use the
len function to count the occurrences:
>>> len([n for n in names if n == "chuck"]) 2