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:

See online demo and code


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:

See online demo and code

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:

See online demo and code

The Output:

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:

See online demo and code

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:

See online demo and code

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:



You may learn more about the Counter here.