Sometimes you need the count of each item in the List. Python comes with a handy tool in the collections module exactly for this task.
First you have to import the Counter.
1
|
from collections import Counter
|
And then create the Counter object with the list as argument.
1
2
|
numbers = [8, 8, 8, 1, 1, 9, 4, 4, 4, 4, 4, 4, 4]
counter = Counter(numbers)
|
You can use counter in various ways.
1
2
3
4
|
# How many times each item appears in the List
print(counter)
# Counter({4: 7, 8: 3, 1: 2, 9: 1})
# Already sorted with the most common items in the front
|
You can get a count of specific item.
1
2
3
4
5
|
print(counter[8])
# 3
print(counter[20])
# If item is not included return value is 0
|
Counter object also comes with a very handy method to return a most common item. You can pass an argument to specify if you want just the most common item or more.
1
2
3
4
5
6
|
most_common = counter.most_common(1)
# [(4, 7)]
most_common = counter.most_common(2)
# [(4, 7), (8, 3)]
# returns List of tuples as (item, count)
|