list.count()
Counts how many items in a list are equal to a given value and returns that number. Gives 0 when there are none.
list.count(x)count(x) goes through the whole list and tells you how many items equal x. A value that is not there gives 0, never an error.
Use it for quick questions such as "how many votes for yes?" or "is this name in the list more than once?".
It looks only at the items of the list itself, not inside them: in a list of lists, or a list of sentences, it compares whole items. And when you need the count of every value, calling count() again and again is slow; collections.Counter does it in one pass.
Parameters
| Parameter | What it is |
|---|---|
xrequired | The value to count. Items are compared with ==, so True also matches 1. |
Return value
An integer, 0 or more.
Examples
1Count votes
votes = ["yes", "no", "yes", "yes", "no"]
print("yes:", votes.count("yes"))
print("no:", votes.count("no"))
print("maybe:", votes.count("maybe"))yes: 3 no: 2 maybe: 0
2Find duplicates
emails = ["[email protected]", "[email protected]", "[email protected]"]
for e in sorted(set(emails)):
if emails.count(e) > 1:
print(e, "appears", emails.count(e), "times")[email protected] appears 2 times
sorted(set(...)) checks each different address once, in a fixed order.
3It counts whole items, not parts
words = ["apple pie", "apple", "pie"]
print(words.count("apple"))
print(sum(w.count("apple") for w in words))1 2
The second line uses str.count() on each string to count the word inside the sentences too.
4Count every value at once
from collections import Counter
sizes = ["M", "L", "M", "S", "M", "L"]
tally = Counter(sizes)
print(tally["M"], tally["L"], tally["S"])
print(tally.most_common(1))3 2 1
[('M', 3)]Common mistakes
Counting with a different type
"5" (text) is not equal to 5 (a number), so it is not counted. Convert first if your data comes from text.
answers = ["5", "3", "5"]
print(answers.count(5))
print(answers.count("5"))0 2
Questions people ask
How do I count occurrences of every item in a list?
Use collections.Counter(items). It builds a dictionary-like object of value → count in one pass.
How do I check if a list has duplicates?
Compare lengths: len(items) != len(set(items)) is True when something appears more than once.
How do I count items that match a condition?
Use sum() with a test: sum(1 for p in prices if p > 10) counts prices above 10.