Tag Archives: Counter

Counting the items in a list in Python

To count the number of a single item in a list, use the count() method:

from random import randint

dishes = ['spam', 'eggs', 'ham']
# Fill a list with 100 randomly selected dishes
orders = [dishes[randint(0, 2)] for i in range(1, 101)]
# Print the count of spam orders
print("spam: {0}".format(orders.count('spam')))
spam: 31

To get the counts of all items, use a collections.Counter

from collections import Counter

counter = Counter(orders)
Counter({'ham': 37, 'eggs': 32, 'spam': 31})