DEV Community

@QED
@QED

Posted on

You can be happy to know Python Counter - How to get the most common elements in a list

I often use Python Counter to count elements of a list. The Counter class is a dict subclass and can be used from Python 3.1. The following is the most simplest example.

from collections import Counter

s = ['a', 'a', 'b']

c = Counter(s)

print(c)  # Counter({'a': 2, 'b': 1})
Enter fullscreen mode Exit fullscreen mode

You can count the specified element of a list in the same way as getting the value of a dictionary by a key.

from collections import Counter

s = ['a', 'a', 'b']

c = Counter(s)

print(c['a'])  # 2
Enter fullscreen mode Exit fullscreen mode

You don't need to create own functions to count items like this.

s = ['a', 'a', 'a', 'b', 'b', 'c']

c = 0

for i in s:
    if i == 'a':
        c = c + 1

print(c)  # 3
Enter fullscreen mode Exit fullscreen mode

Get the most common elements

The most_common() is one of the greatest method in the Counter class.

from collections import Counter

s = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c']

c = Counter(s)

common = c.most_common(2)

print(common)  # [('a', 4), ('b', 3)]
Enter fullscreen mode Exit fullscreen mode

This function returns the n most common elements as a list and n is 2 in the above case. If n is omitted, it returns all the elements and counts.

The detailed explanation is here. The collections module, which has the Counter class, helps us to shortcut developing. If you want to create the tiny or primitive function that might need the for statement, it's important to rethink if it's been already coded by Python Software Foundation.

Top comments (0)