Python Reference ยท Lists, Tuples and Ranges
Python list.count() method
Reference for Python list.count(): count how many times a value appears in a list, how equality is decided, performance, and when Counter is the better tool.
The count() method returns how many items in the list are equal to the value you pass. It scans the whole list from start to end and returns an integer, which is 0 when the value is not present. It never raises an error for a missing value.
Use it for a quick tally of one value. If you need counts for many different values, collections.Counter does it in a single pass.
print([1, 2, 2, 3, 2].count(2)) # 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.count(value)
| Name | Description |
|---|---|
value |
The object to look for. Items are compared to it with ==. |
Return value: an int, the number of matching items (0 or more).
Raises: nothing for a missing value.
Usage notes
- Equality, not identity. Items match when
item == valueis true (identity is checked first as a shortcut), so1,1.0andTrueall count as the same value, while"1"does not. - Nested lists compare by content.
[[1, 2], [1, 2]].count([1, 2])is2. - Linear time. Every call walks the entire list. Calling
count()for each distinct item inside a loop is O(n squared); useCounterinstead. - Counting by a condition. For "how many items are greater than 2" use
sum(1 for x in data if x > 2);count()only compares for equality. - NaN.
float("nan")is never equal to anything, even itself, but ananthat is the very same object is found by the identity shortcut. Treat counting NaNs withmath.isnan()instead. - Same method on other types:
tuple.count()andstr.count(sub)exist. The string version counts non-overlapping substrings and acceptsstartandend; the list version takes no range. - Presence only? If you only need to know whether a value exists, use
value in items, which stops at the first match.
Related
list.index(),list.remove(),str.count(),len(),sum(),list- Lessons: List methods, Collections module