list.count()
Python · Lists
Theory
.count(value) walks through the whole list and returns how many items are equal (==) to value. For sales = [100, 250, 250, 300], sales.count(250) is 2. A value that does not appear simply gives 0, never an error, so count() is also a safe way to check presence when you need the number anyway.
Because it compares with ==, values that are equal but of different types are counted together: in [1, True, 1.0], count(1) is 3, since True == 1 and 1.0 == 1. Each call scans the entire list, O(n). Calling count() for every distinct value inside a loop therefore becomes O(n squared) and gets slow on large data. To count all values at once, use collections.Counter(sales), which does a single pass and returns a dict-like object of value to count.
Why we use it
Frequency questions come up constantly: how many orders were cancelled, how many times a city appears, are there duplicate IDs? count() answers them for a single value in one line.
When to use it
Use count() for a quick count of one value in a small or medium list. Use collections.Counter or pandas value_counts() when you need counts for every value, and sum(1 for x in items if condition) for counting by a rule.
How it works
- Call sales.count(250)
- Set a counter to 0
- Visit each item in the list
- Is the item == 250? Yes: Add 1 to the counter. No: Leave the counter as is.
- After the last item, return the counter
- print shows 2
Syntax
list.count(value)Example
sales = [100, 250, 250, 300]
print(sales.count(250))Key points
- Returns 0, not an error, if the value is absent
- Counts with ==, so True and 1.0 count as 1
- Scans the whole list every call (O(n))
- Use collections.Counter to count every value in one pass
- Useful for quick frequency checks without a full Counter