The Counter subclass in Python

Important points about the Counter:

  • The counter is a subclass of the dict (From collections library).
  • The Python Counter tool is used to count the hashtable objects.
  • The elements of the iterable like lists can be counted by using Counter.
  • It may also count elements initialized from another mapping or counter.
  • The Counter is an unordered collection. The elements are stored as dictionary keys and counts as dictionary values.
  • You may perform arithmetic operations on Counter objects to get aggregated results.

You have to import Counter from collections as follows:

from collections import Counter

Read the following section for examples to make things further clearer.

An example of counting list elements by Counter

In the following example of using Counter, a list of few elements is created that contains duplicate elements. After that, the Counter is used to get the count of each element in the list:

#An example of Collections Counter

from collections import Counter



lang_list = ['Python', 'C++', 'C', 'Java', 'Python', 'C', 'Python', 'C++', 'Python', 'C']



print(Counter(lang_list))

Counter

The Output of the code is:

You can see the displayed dictionary contains elements in the list and count of each element. The elements became the keys and their count became the values.

You may also display the items as follows:

print (Counter(lang_list).items())

The output:

dict_items([(‘Java’, 1), (‘C’, 3), (‘Python’, 4), (‘C++’, 2)])

Getting the count of specific item in a list

You may also get the count of a specific element in an iterable. See the example below where a list is created just like above example. The program displays the count of only ‘Python’ in the list rather than all elements:

#An example of Collections Counter to get specific element count

from collections import Counter



lang_list = ['Python', 'C++', 'C', 'Java', 'Python', 'C', 'Python', 'C++', 'Python', 'C']



C = Counter(lang_list)

print("The occurrance of Python is: " ,C['Python'])

The Output:

Counter item

An example of getting count in a String

The beauty of the Counter Python subclass is that you may use it for any iterable. Though Python has a function to count elements in list and strings, the Counter works with the tuple, list, string and other iterables. So, its scope is wider.

For this example, a string is created and Counter is used simply to return the count of each character:

#An example Counter with string

from collections import Counter



str_count = "Hello World"



C = Counter(str_count)



print(C)

The Output:

Counter({'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1, ' ': 1, 'e': 1, 'H': 1})

>>> 

As such, a string is a sequence of characters so occurrence of each character is displayed as using the Counter.

Get the count of single character in the string

Just like the list items, you may get the count of a specific letter after using the counter with string sequence. Have a look at the following example:

from collections import Counter



str_count = "Hello World"



C = Counter(str_count)



print("The occurrence of 'l' is: " ,C['l'])

The Output:

The occurrence of ‘l’ is:  3

An example of tuple with numeric items

In this example, the Counter is used with a tuple that contains numeric items. So, you may also get the digit counts in a sequence by using the Counter as shown in the example below:

#An example Counter with numbers in Tuple

from collections import Counter



tup_counter = (7,9,3,4,5,7,3,2,7,4,3,7)



C = Counter(tup_counter)



print(C)

The output of the above example is:

Counter({7: 4, 3: 3, 4: 2, 2: 1, 5: 1, 9: 1})

Performing arithmetic operations

As mentioned in introductory part, you may perform arithmetic operations as well. For example:

from collections import Counter



counter1 = Counter([5, 7, 10])

counter2 = Counter([1, 5, 7])



print(counter1 + counter2)



print(counter1 - counter2)



print(counter1 & counter2)

Output:

Counter({5: 2, 7: 2, 1: 1, 10: 1})

Counter({10: 1})

Counter({5: 1, 7: 1})

 

You may learn more about the Counter here.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!