Tips For Python

Ignacio Ruiz
2 min readJun 15, 2021

The one about the counter

Hey! I’m back with another tip for python that you can use to better your coding and speed up your process! Today we’ll talk about Python Counter.

Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a sub-class available inside the dictionary class.

The counter is a sub-class available inside the dictionary class. Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object.

Basically, Python Counter takes into input a list, tuple, dictionary, string, which are all iterable objects, and it will give you output that will have the count of each element. We will start by loading Counter.

from Collections import Counter

Then let’s create a list that contains the items that we want to count.

letters=["a","a","e",'r',"b","x","y","w","e","x","a","r","a","e"]

The list has a bunch of letters. When you use Counter on this list, it will count how many times each letter is present. The output if Counter is used on the list is

Counter(letters)Counter({'a': 4, 'e': 3, 'r': 2, 'b': 1, 'x': 2, 'y': 1, 'w': 1})

But Counter also works with strings! In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.

t_string="Hello! I am a string that is gonna be tested on!"
Counter(t_string)
Counter({'H': 1,'e': 4,'l': 2,'o': 3,'!': 2,' ': 10,'I': 1,'a': 4,
'm': 1,'s': 3,'t': 5,'r': 1,'i': 2,'n': 4,'g': 2,'h': 1,'b': 1,
'd': 1})

Notice how it counted the empty spaces as well as how it counted the capital and lower case “I”,”H” separately. So if you want to use it, make sure that you’re formatting your strings accordingly.

You are also able to store it as needed. You can store your counter as is in a variable or you can convert it in a dictionary for later use.

Counter(letters)Counter({'a': 4, 'e': 3, 'r': 2, 'b': 1, 'x': 2, 'y': 1, 'w': 1})var_a = Counter(letters)print(var_a)
Counter({'a': 4, 'e': 3, 'r': 2, 'b': 1, 'x': 2, 'y': 1, 'w': 1})
var_b = dic(Counter(letters))
print(var_b)
{'a': 4, 'e': 3, 'r': 2, 'b': 1, 'x': 2, 'y': 1, 'w': 1}

And since Counter is a dictionary item, depending on how you want to use it, you are able to call its items, keys, and values like a regular dictionary.

print(Counter(letters).items())
dict_items([('a', 4), ('e', 3), ('r', 2), ('b', 1), ('x', 2), ('y', 1), ('w', 1)])
print(Counter(letters).keys())
dict_keys(['a', 'e', 'r', 'b', 'x', 'y', 'w'])
print(Counter(letters).values())
dict_values([4, 3, 2, 1, 2, 1, 1])

So give it a try! See how it can improve your code!

--

--