snippetpythonCritical
How do I count the occurrences of a list item?
Viewed 0 times
occurrenceshowlisttheitemcount
Problem
Given a single item, how do I count occurrences of it in a list, in Python?
A related but different problem is counting occurrences of each different element in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see Using a dictionary to count the items in a list.
A related but different problem is counting occurrences of each different element in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see Using a dictionary to count the items in a list.
Solution
If you only want a single item's count, use the
Important: this is very slow if you are counting multiple different items
Each
If you want to count multiple items, use
count method:>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3Important: this is very slow if you are counting multiple different items
Each
count call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks, which can be catastrophic for performance.If you want to count multiple items, use
Counter, which only does n total checks.Code Snippets
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3Context
Stack Overflow Q#2600191, score: 2562
Revisions (0)
No revisions yet.