Python: Counter from the collection module

Anshul Jain
1 min readMar 20, 2021
Photo by Adi Goldstein on Unsplash

A Counter() in Python is essentially a container that helps the programmer keep, as the name suggests, ‘counts’ of the values. It does so by storing the elements as dictionary keys and the frequency of the element as the dictionary values.

How and where do we import it from you ask?

How do we use it in a code?

→→→→→→→→→→→

The above snippet uses a list of words and pass it as an argument to the counter object. The counter object then save each distinct word to a dictionary key and the frequency of it’s appearance as the corresponding dictionary value.

The output of the above code snippet:

Counter({'difficult': 3,
'navigate': 1,
'slack': 4,
'channel': 3,
'user': 1,
'remember': 2,
'link': 1,
'access': 4,
'outside': 1,
'password': 1,
'different': 2,
'account': 1,
'make': 1,
'inconvenient': 1,
'device': 1,
'new': 1,
'laptop': 1,
'old': 1,
'almost': 1,
'impossible': 1,
'forget': 1,
'.': 1})

I used an example using words instead of numbers but you can find tons of them online, which works in precisely the similar manner. However, this is a go-to approach for most NLP projects where you could be using them for thing like bi-grams among others.

See ya!

--

--

Anshul Jain
0 Followers

I am a Machine Learning Engineer and an A.I. fanatic.