inspection
list.count
Returns the number of times x appears in the list. Comparison uses equality; returns 0 if x is not present (never raises).
list.count(x) Parameters
| Parameter | Purpose |
|---|---|
| x | Value to count; compared with ==. |
| (no range) | Unlike index, count has no start/stop — it always scans the whole list. |
Examples
>>> [1, 2, 2, 3, 2].count(2)
3 Counts all equal elements.
>>> [1, 2, 3].count(9)
0 Missing values return 0 — no exception.
>>> [1.0, 1, True].count(1)
3 == treats 1, 1.0, and True as equal — a classic gotcha.
>>> from collections import Counter
>>> Counter([1, 2, 2, 3])[2]
2 For many queries, Counter is O(n) once instead of O(n) per call.
Gotcha
1 == 1.0 == True in Python, so count collapses booleans and numerics together. For repeated counts, build a collections.Counter once instead of calling count in a loop (O(n²)).
Related methods
list.index
Returns the zero-based index of the first item equal to x within the optional [start, end) range. Raises ValueError if no match is found.
x in list
Membership test operator that returns True if any element equals x, else False. Runs in O(n) — for repeated lookups, convert to a set (O(1) per test).
len (built-in)
Returns the number of elements in the list as an int. O(1) because CPython lists track their length internally.
← All Python list methods · Dict methods · list vs tuple vs set