If you only want a single item’s count in the list, then use the count
method. Use the Python Counter method to count occurrences of all items in the list.
Use Counter
if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:
Python counts occurrences of all items in the list
Simple example code.
from collections import Counter
l1 = [1, 2, 3, 4, 1, 4, 1]
res = l1.count(1)
print(res)
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
all = Counter(z)
print(all)
print(Counter(l1))
Output:
Counting all items with count()
To count the occurrences of items in l
one can simply use a list comprehension and the count()
method
[[x,l.count(x)] for x in set(l)]
(or similarly with a dictionary dict((x,l.count(x)) for x in set(l))
)
Example:
>>> l = ["a","b","b"]
>>> [[x,l.count(x)] for x in set(l)]
[['a', 1], ['b', 2]]
>>> dict((x,l.count(x)) for x in set(l))
{'a': 1, 'b': 2}
Counting all items with Counter()
Alternatively, there’s the faster Counter
class from the collections
library
Counter(l)
Example:
>>> l = ["a","b","b"]
>>> from collections import Counter
>>> Counter(l)
Counter({'b': 2, 'a': 1})
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.