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']
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 True
values:
>>> sum(map(lambda x: x == "chuck", names)) 2
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 if
:
>>> [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