To count in Python, use len(x) for the total number of items, and x.count(value) for how many times one value appears in a list or string. To count every distinct item at once, pass the list or string to collections.Counter.
items = ['a', 'b', 'a', 'c', 'a']
len(items) # 5 total items
items.count('a') # 3 occurrences of 'a'
text = 'spam, spam, spam'
text.count('spam') # 3 occurrences of a substring
How to count the items in a list
len() returns the number of items. The Python docs describe it as returning "the length (the number of items) of an object", and the argument can be a sequence such as a string, bytes, tuple, list or range, or a collection such as a dictionary, set or frozen set.
colors = ['red', 'blue', 'red', 'green']
print(len(colors))
Example output:
4
A nested list counts its inner lists as single items, so len([[1, 2], [3, 4, 5]]) is 2, not 5.
How to count how many times a value appears in a list
Use list.count(value). The docs say it returns "the total number of occurrences of value in sequence". It compares with equality, and it returns 0 when the value is absent instead of raising an error.
colors = ['red', 'blue', 'red', 'green']
print(colors.count('red'))
print(colors.count('purple'))
Example output:
2
0
count() scans the whole list on every call. That is fine for one value. If you need the count of many different values, calling it in a loop rescans the list each time, and Counter (below) does the job in one pass.
How to count a letter or word in a string
Use str.count(sub[, start[, end]]). It returns the number of non-overlapping occurrences of sub in the range [start, end], where the optional arguments work like slice indexes. These examples are from the Python documentation:
>>> 'spam, spam, spam'.count('spam')
3
>>> 'spam, spam, spam'.count('spam', 5)
2
>>> 'spam, spam, spam'.count('spam', 5, 10)
1
>>> 'spam, spam, spam'.count('eggs')
0
>>> 'spam, spam, spam'.count('')
17
Two details catch people out:
- Matching is case-sensitive.
'Spam spam'.count('spam')is 1. Lowercase the string first withtext.lower().count('spam')to count both. - Overlaps are not counted. After a match, the search resumes after it, so
'aaaa'.count('aa')is 2, not 3.
An empty substring returns the length of the string plus one, as the last line above shows (the string has 16 characters).
Note that str.count() takes a substring, so 'cat dog cat'.count('cat') also matches the cat inside 'concatenate'. To count whole words, split first: 'cat dog cat'.split().count('cat') counts list items, so only exact words match.
How to count every item at once with Counter
collections.Counter is a dictionary subclass for counting. Per the docs, elements are counted from an iterable, and a string is an iterable of characters:
from collections import Counter
print(Counter('abracadabra'))
print(Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']))
Example output (the first is the order the docs show for most_common; the exact printed form can vary slightly between Python versions):
Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
Counter({'blue': 3, 'red': 2, 'green': 1})
Useful behaviour from the documentation:
most_common(n)returns the n most common elements and their counts, most common first. With n omitted orNone, it returns all of them. Elements with equal counts keep the order in which they were first encountered.Counter('abracadabra').most_common(3)returns[('a', 5), ('b', 2), ('r', 2)].- A missing item returns
0instead of raisingKeyError:Counter(['eggs', 'ham'])['bacon']is 0. - Setting a count to zero does not remove the entry. Use
delto remove it. total()returns the sum of all the counts. It was added in Python 3.10, so it is not available on older versions.
How to count items that match a condition
When the test is more than equality, such as "how many numbers are greater than 10", combine sum() with a generator expression. bool is a subclass of int, and sum() adds up the items of an iterable, so each True adds 1:
numbers = [4, 12, 7, 30, 15]
print(sum(1 for n in numbers if n > 10))
print(sum(n > 10 for n in numbers))
Example output:
3
3
The first form is more explicit and is easier to read for people new to Python. For a list you also want to keep, len([n for n in numbers if n > 10]) works, see Python list comprehension for the syntax. It builds the whole filtered list in memory, which the sum() forms avoid.
Which one to use
| You want | Use |
|---|---|
| Total items or characters | len(x) |
| Occurrences of one value in a list | my_list.count(value) |
| Occurrences of a substring in a string | my_string.count(sub) |
| Count of every distinct item | Counter(x) |
| Items matching a condition | sum(1 for item in x if test) |
If it still gives the wrong number
- Count is 0 but you can see the text. Check case, and check for stray whitespace or different characters that look alike.
repr(text)shows hidden characters such as\nand trailing spaces. - A
TypeErrorfromlist.count(). It needs the value to look for as its one argument. For a total, uselen(). - A
TypeErrorfromstr.count()on a number. The substring must be a string. Convert it:'a1b1'.count(str(1)). - Counts of a list of lists look wrong.
list.count()compares whole items, so[[1], [1]].count(1)is 0 and[[1], [1]].count([1])is 2.
Frequently asked questions
- What is the difference between len() and count() in Python?
- len(x) returns the total number of items in a list, string or other collection. x.count(value) returns how many times one specific value appears in it. For the list ['a', 'b', 'a'], len gives 3 and count('a') gives 2.
- Does str.count() count overlapping matches?
- No. The Python documentation says str.count() returns the number of non-overlapping occurrences of the substring. 'aaaa'.count('aa') returns 2, not 3, because after the first match at index 0 the search resumes at index 2.
- How do I count every item in a list at once?
- Pass the list to collections.Counter. Counter(['red', 'blue', 'red']) gives a dictionary-like object mapping each item to its count. Calling .most_common() returns the items sorted from most to least frequent.
- What does Counter return for an item that is not in it?
- Zero. Unlike a normal dictionary, a Counter returns a count of 0 for a missing item instead of raising KeyError.