Counter function in Python – Collections

The Counter Function in Python is used to count the number of repeated elements in an iterable object, such as a List, String or Tuple. The Counter function belongs to the Collections module in Python, from where it needs to be imported before using it.

from collections import counter

In this tutorial we will cover all the different ways you can use this function.


Counter with Lists

First let’s use the Counter Function with a Python List. All we need to do is pass in the List object into the Counter function as an argument. This will return to us a Counter object in the form of a dictionary of key-value pairs.

The “key” will be the element from the list, and the “value” will be the number of times it was found. So 5:3 means that the number 5 was found 3 times.

from collections import Counter

mylist = [3,4,5,1,2,4,6,5,3,2,6,5,4,8,5,6,5,5]

counter = Counter(mylist)
print(counter)

Printing out the counter object gives us the following:

Counter({5: 6, 4: 3, 6: 3, 3: 2, 2: 2, 1: 1, 8: 1})

Here we can clearly see that “5” is the most repeated number, followed by 4 and 6.

If you wish to find the out the number of occurrences for any single value, you can do the following:

print(counter[5])
print(counter[4])
print(counter[8])
6
3
1

If you try accessing an element that doesn’t exist, it will return 0.


Counter with Strings

Using the Counter Function with strings is no different from using it with a List or Tuple.

from collections import Counter

counter = Counter("HelloWorld")
print(counter)
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, 'W': 1, 'r': 1, 'd': 1})
print(counter['l'])
print(counter['H'])
print(counter['h'])
3
1
0

Remember that capitalization matters!


Accessing the Counter Elements

There are many different ways of accessing the Counter elements, and various operations that can be applied on individual elements. There are even operations that we can apply between different counter objects!

Updating Elements

You can update the values in a Counter object, the same way you would in a regular Python Dictionary.

from collections import Counter

mylist = [3,4,5,1,2,4,6,5,3,2,6,5,4,8,5,6,5,5]

counter = Counter(mylist)

print(counter)
counter[8] = 10
print(counter)
Counter({5: 6, 4: 3, 6: 3, 3: 2, 2: 2, 1: 1, 8: 1})
Counter({8: 10, 5: 6, 4: 3, 6: 3, 3: 2, 2: 2, 1: 1})

Deleting Elements

Sometimes you may wish to delete elements from the Counter object. For example, if you update the value of a number to 0, it will not remove itself from the Counter object until you delete it.

from collections import Counter

mylist = [3,4,5,1,2,4,6,5,3,2,6,5,4,8,5,6,5,5]

counter = Counter(mylist)

print(counter)
del counter[8]
print(counter)
Counter({5: 6, 4: 3, 6: 3, 3: 2, 2: 2, 1: 1, 8: 1})
Counter({5: 6, 4: 3, 6: 3, 3: 2, 2: 2, 1: 1})

Iterating through the Counter Object

Iterating through the Counter object can seem a little tricky, especially because it could be holding values of various datatypes. Below is a general way of iterating through it, that will work in all situations.

from collections import Counter

mylist = [3,4,5,1,2,4,6,5,3,2,6,5,4,8,5,6,5,5]

counter = Counter(mylist)

for key in counter.keys():
    print(f"Key: {key}   Value: {counter[key]}")
Key: 3   Value: 2
Key: 4   Value: 3
Key: 5   Value: 6
Key: 1   Value: 1
Key: 2   Value: 2
Key: 6   Value: 3
Key: 8   Value: 1

Convert back to List

For easier use, you can convert the Counter Object back into a list using the list() constructor. It won’t be the exact same however. All the elements will be grouped together, for e.g: All 1’s will be together, all 2’s will be together and so on.

from collections import Counter

mylist = [3,4,5,1,2,4,6,5,3,2,6,5,4,8,5,6,5,5]

counter = Counter(mylist)
print(list(counter.elements()))
[3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 1, 2, 2, 6, 6, 6, 8]

Most Common Elements

Another handy method that is available to us is most_common(n). This function takes an argument “n” and returns “n” number of the most common key-value pairs. Passing in 1 will give you the most common, passing in 2, will give you to the two most common.

from collections import Counter

mylist = [3,4,5,1,2,4,6,5,3,2,6,5,4,8,5,6,5,5]

counter = Counter(mylist)
print(counter.most_common(3))
[(5, 6), (4, 3), (6, 3)]

Adding and Subtracting Counter Objects

As mentioned earlier, you can perform the addition and subtraction operations between two counter objects. This will add or subtract the counts for each element.

from collections import Counter

mylist1 = [3,4,5,1,2,4,6,5,3,2,6,5,4,8,5,6,5,5]
mylist2 = [4,6,7,6,4,5,4,2,2,3,3,2,4,5]

counter1 = Counter(mylist1)
counter2 = Counter(mylist2)

counter3 = counter1 + counter2
print(counter3)
Counter({5: 8, 4: 7, 2: 5, 6: 5, 3: 4, 1: 1, 8: 1, 7: 1})

You can also subtract them. This may cause some elements to be removed, if their counts drop to 0 or below.

counter3 = counter1 - counter2
print(counter3)
Counter({5: 4, 1: 1, 6: 1, 8: 1})

This marks the end of the Counter Function in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments