In this post we will be creating a script that will count the occurrences of an item within a list. See below the list we’ll be using in this example, consisting of ten items.
List=['Abraham', 'John', 'Luke', 'Fry', 'Latifah', 'Joseph', 'John', 'Nick', 'Amy', 'John']
Because this is a small list and we know it can be done relatively quick we will use the count method as seen in the snippet of code below. Here we are counting the number of times the name ‘John’ appears in our list.
Count=List.count('John')
print(Count)
The above would return ‘3’. If you are trying to achieve the same with a larger list or in the context of something a little more complex, it is recommended to use the Counter method instead as it is a lot more efficient. See the snippet of code below. Where we are again counting the number of times the name ‘John’ appears in our list.
from collections import Counter
List=['Abraham', 'John', 'Luke', 'Fry', 'Latifah', 'Joseph', 'John', 'Nick', 'Amy', 'John']
Count=Counter(List)
print(Count)
The output for the above would be seen as.
Counter({'John': 3, 'Abraham': 1, 'Luke': 1, 'Fry': 1, 'Latifah': 1, 'Joseph': 1, 'Nick': 1, 'Amy': 1})