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: 0How it works
votes.count("red")looks through the whole list and counts the items equal to"red".Counter(votes)goes through the list once and builds a dictionary from each item to its count. If you callcount()once for every different item, the list is read again each time.Counterreads it once.most_common(1)gives a list with the one most common item and its count, as a tuple.- A
Countergives 0 for an item it has not seen. A normal dictionary would raise aKeyError.
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.