Python Counter – Detailed Tutorial

In this Python tutorial, we will discuss the Python counter. Also, we will see these below topics as:

  • What is the python counter?
  • Counter() python
  • Python counter string
  • Python counter list
  • Python counter dictionary
  • Python counter tuple
  • Python updating counter
  • Python counter subtract()
  • Deleting an element from a counter
  • Python counter sort by frequency
  • Python counter iterate
  • Python counter increment

What is the python counter?

  • Python counter is a container that keeps the count of each element present in the container.
  • Python counter is an unordered collection of items where items are stored as dictionary key-value pairs.
  • Counter class in python is a part of the collections module and subclass of a dictionary.
  • When you try accessing an element that is not present, then the counter object will return zero.

Counter() python

Now, let us understand counter() in python.

  • In python counter() is a subclass of the dictionary class.
  • To use the counter we will first import “from collections import Counter”.
  • We need to pass the list to the counter() function.
  • It will return back the dictionary which will have the count of each element.

Example:

from collections import Counter
l = ['rose','tulips','sunflowers','tulips','rose']
my_count = counter(l)
print(my_count)

After writing the above code (counter() python), when you will print “my_count” then the output will appear as “Counter({‘rose’: 2, ‘tulips’: 2, ‘sunflower’: 1})”. Here, the list has elements rose, tulips, and sunflower. When we use the counter on this list it will count how many times rose, tulips and sunflower is present.

You can refer to the below screenshot for counter() python.

Counter() python
Counter() python

Python counter string

  • In python, the string can be created by enclosing characters in the double-quotes.
  • A string is passed to the counter. It returns the dictionary format with key and value pair.
  • Here, the key is the element and the value is the count and it gives the count of the spaces in the string.

Example:

from collections import Counter
my_str = "Welcome to all"
my_count = counter(my_str)
print(my_count)

After writing the above code (python counter string), when you will print “my_count” then the output will appear as “Counter({‘l’: 3, ‘e’: 2, ‘o’: 2, ‘ ‘: 2, ‘W’: 1, ‘c’: 1, ‘m’: 1, ‘t’ : 1, ‘a’ : 1})”. Here, my_str is “Welcome to all”. When we use the counter on this string it will count the value of the element. It also considers space as an element.

You can refer to the below screenshot for python counter string

Python counter string
Python counter string

Python counter list

In python, a list is an iterable object. The elements in the list are given to the counter and it will convert it. Where the element will become keys and the values will be the count of the elements of the given Python list.

Example:

from collections import Counter
my_lst = ['y', 'u', 'm', 'm', 'y']
my_count = counter(my_lst)
print(my_count)

After writing the above code (python counter list), when you will print “my_count” then the output will appear as “Counter({‘y’: 2, ‘m’: 2, ‘u’: 1})”. Here, the list has elements [‘y’, ‘u’, ‘m’, ‘m’, ‘y’]. When we use the counter on this list it will count each element in the list.

You can refer to the below screenshot for python counter list.

Python counter list
Python counter list

Python counter dictionary

A dictionary in python is key-value pairs. When the dictionary is given to the counter, it will be converted to a hashtable objects. The elements will become keys and the values will be the count of the elements from the Python dictionary.

Example:

from collections import Counter
my_dictionary = ['y':2, 'u':1, 'm':1, 'y':2]
my_count = counter(my_dictionary)
print(my_count)

After writing the above code (python counter dictionary), when you will print “my_count” then the output will appear as “Counter({‘y’: 2, ‘u’: 1, ‘m’: 1})”. Here, the dictionary has a key-value pair. When the dictionary is given to the counter, the counter function will find the count of each of the key from the given dictionary.

You can refer to the below screenshot for python counter dictionary.

Python counter dictionary
Python counter dictionary

Python counter tuple

In python, a tuple is a collection of objects written inside the round brackets. Ones the tuple is given to the counter, it will be converted to a hashtable object. Here, the element will be keys and the values will be the count of the elements from the Python tuple.

Example:

from collections import Counter
my_tuple = ('red', 'pink', 'green', 'pink', 'green', 'red')
my_count = counter(my_tuple)
print(my_count)

After writing the above code (python counter tuple), when you will print “my_count” then the output will appear as “Counter({‘red’: 2, ‘pink’: 2, ‘green’: 2})”. Here, the tuple has elements (‘red’, ‘pink’, ‘green’, ‘pink’, ‘green’, ‘red’). When the tuple is given to the counter, then the value will be the count of the elements from the given tuple.

You can refer to the below screenshot for python counter tuple.

Python counter tuple
Python counter tuple

Python updating counter

We can add values to the counter by using update() method. Here, we have created an empty counter “my_count = Counter()” and updated using ” my_counter.update()” method.

Example:

from collections import Counter
my_count = Counter()
my_counter.update([101, 201, 101, 301, 201])
print(my_count)
my_counter.update([101, 301, 201])
print(my_count)

After writing the above code (python updating counter), when you will print “my_count” then the output will appear as “Counter({101: 2, 201: 2, 301: 1}) Counter({101: 3, 201: 3, 301: 2})”. Here, the update() method is used to update the data. The counter data will be increased after updating.

You can refer to the below screenshot for python updating counter.

Python updating counter
Python updating counter

Python counter subtract()

In this we will see how counter subtract() function works

The Counter subtract() method is used to subtract one element counts from another counter. It is used to deduct the elements from another counter.

Example:

from collections import Counter
my_counter1 = Counter({'a':8, 'b':12, 'c':20})
my_counter2 = Counter({'a':5,  'b':5})
my_counter1.subtract(my_counter2)
print(my_counter1)

After writing the above code (python counter subtract()), when you will print “my_counter1” then the output will appear as “Counter({‘c’: 20, ‘b’: 7, ‘a’:3})”. Here, the counter will return the dictionary after deducting the elements from another counter.

You can refer to the below screenshot for python counter subtract().

Python counter subtract()
Python counter subtract()

Deleting an element from a counter

Now, let us see how to delete an element from a counter.

To delete an element from a counter we will use del then, the particular element will be deleted and it will return a dictionary with the rest element.

Example:

from collections import Counter
dictionary = {'red':4, 'pink':12, 'green':10}
del dictionary["green"]
print(counter(dictionary))

After writing the above code (deleting an element from a counter), when you will print “Counter(dictionary)” then the output will appear as “Counter({‘pink’: 12, ‘red’: 4})”. Here, the del dictionary[“green”] is used to delete the particular element.

You can refer to the below screenshot for deleting an element from a counter

Deleting an element from a counter
Deleting an element from a counter

Python counter sort by frequency

In python, to sort by frequency we will use a built-in Counter and it will return each word with the associated frequency count in sorted order.

Example:

from collections import Counter
val = {'x', 'b', 'x', 'b', 'g', 'x'}
s = Counter(val)
print(s)

After writing the above code (python counter sort by frequency), when you will print “s” then the output will appear as “Counter({‘x’: 3, ‘b’: 2, ‘g’:1})”. Here, the counter will return the dictionary with key and associated frequency in sorted order.

You can refer to the below screenshot for python counter sort by frequency.

Python counter sort by frequency
Python counter sort by frequency

Python counter iterate

The for loop is used to iterate through each element. The counter will have a string as an iterable item. The counter object will return itertool for all elements.

Example:

import collections import Counter
c = Counter('pythonguides')
for i in c.elements():
   print(i, end = " ")

After writing the above code (python counter iterate), when you will print then the output will appear as “p y t h o n g u i d e s”. Here, we can see that the string iterates and it will print the elements of the counter object.

You can refer to the below screenshot for python counter iterate

Python counter iterate
Python counter iterate

Python counter increment

We will use the counter object from the collection module. We have created an empty counter() and every time the value is incremented by 1 and it is calculating the frequency of the value.

Example:

from collection import Counter
f = Counter()
for i in range(0, 8):
    f[i] += 1
print(f)

After writing the above code (python counter increment), when you will print “f” then the output will appear as “Counter({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1})”. Here, the counter will return the dictionary with key and associated frequency within the range.

You can refer to the below screenshot for python counter increment.

Python counter increment
Python counter increment

You may like the following Python tutorial:

In this Python tutorial, we have learned about the python counter. Also, We covered these below topics:

  • What is the python counter?
  • Counter() python
  • Python counter string
  • Python counter list
  • Python counter dictionary
  • Python counter tuple
  • Python updating counter
  • Python counter subtract()
  • Deleting an element from a counter
  • Python counter sort by frequency
  • Python counter iterate
  • Python counter increment