PythonMastery
Python programs · Lists · beginner

Count occurrences of an element in a list in Python

Count how many times an item appears in a list with list.count(), and count every item at once with collections.Counter.

To count one item, use the list's count() method. To count every item, use Counter from the collections module.

The program

python
from collections import Counter

votes = ["red", "blue", "red", "green", "blue", "red"]

print("Votes for red:", votes.count("red"))

counts = Counter(votes)
print(counts)
print("Winner:", counts.most_common(1))
print("Votes for purple:", counts["purple"])
output
Votes for red: 3
Counter({'red': 3, 'blue': 2, 'green': 1})
Winner: [('red', 3)]
Votes for purple: 0

How it works

Another way: a dictionary by hand

This is what Counter does for you:

python
votes = ["red", "blue", "red", "green", "blue", "red"]

counts = {}
for vote in votes:
    counts[vote] = counts.get(vote, 0) + 1

print(counts)
output
{'red': 3, 'blue': 2, 'green': 1}

counts.get(vote, 0) gives the current count, or 0 the first time a colour is seen.

Related programs: Frequency table from a list.

Learn the idea: Lists & Sequences, collections: The Stdlib's Hidden Power, Dictionaries

A longer explanation: Count anything with collections.Counter