What is 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.

Why use Python Counter?

Here, are major reasons for using Python 3 Counter:

  • The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.
  • It allows you to count the items in an iterable list.
  • Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.
  • A Counter can also count elements from another counter

In this Python tutorial you will learn:

Introduction to Python Counter

Python Counter takes in 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.

Syntax:

Counter(list)

Consider you have a following list :

list1 = ['x','y','z','x','x','x','y', 'z']

The list has elements x , y and z.When you use Counter on this list , it will count how many times x , y and z is present. The output if counter is used on list1 should be something like :

Counter({'x': 4, 'y': 2, 'z': 2})

So we have the count of x as 4, y as 2 and z as 2.

To make use of Counter we need to import it first as shown in the below given example:

from collections import Counter

Here is a simple example , that shows the working of Counter module.

from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2})

Counter with String

In Python, everything is an object and string is an object too. Python string can be created simply by enclosing characters in the double quote. Python does not support a character type. These are treated as strings of length one, also considered as a substring.

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.

Example:

from collections import Counter
my_str = "Welcome to Guru99 Tutorials!"
print(Counter(my_str))

Output:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

Counter with List

A list is an iterable object that has its elements inside square brackets.

The elements in the list when given to the Counter will be converted to a hashtable objects wherein the elements will become keys and the values will be the count of the elements from the list given.

For example ['x','y','z','x','x','x','y','z']. Once you give the list the Counter, it will give you the count of each element in the list.

from collections import Counter
list1 = ['x','y','z','x','x','x','y','z']
print(Counter(list1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2})

Counter with Dictionary

A dictionary has elements as key/value pair, and they are written inside curly brackets.

Once the dictionary is given to the Counter, it will be converted to a hashtable objects wherein the elements will become keys, and the values will be the count of the elements from the dictionary given.

For example : {'x': 4, 'y': 2, 'z': 2, 'z': 2}. The Counter function will try to find the count of each of the key in the given dictionary.

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2, 'z': 2}
print(Counter(dict1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2})

Counter with Tuple

Tuple is a collection of objects separated by commas inside round brackets. Counter will give you the count of each of the elements in the tuple given.

Once the tuple is given to the Counter, it will be converted to a hashtable object wherein the elements will become keys and the values will be the count of the elements from the tuple given.

from collections import Counter
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))

Output:

Counter({'x': 4, 'y': 2, 'z': 2})

Accessing, Initializing and Updating Counters

Initializing Counter

A Counter can be initialized by passing string value, list, dictionary, or tuple as shown below:

from collections import Counter
print(Counter("Welcome to Guru99 Tutorials!"))   #using string
print(Counter(['x','y','z','x','x','x','y', 'z'])) #using list
print(Counter({'x': 4, 'y': 2, 'z': 2})) #using dictionary
print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple

You can also initialize a empty Counter as shown below:

from collections import Counter
_count = Counter()

Updating Counter

You can add values to the Counter by using update() method.

_count.update('Welcome to Guru99 Tutorials!')

The final code is :

from collections import Counter
_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print(_count)

The output is:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

Accessing Counter

To get the values from the Counter, you can do as follows:

from collections import Counter

_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print('%s : %d' % ('u', _count['u']))
print('\n')
for char in 'Guru':
    print('%s : %d' % (char, _count[char]))

Output:

u : 3

G : 1
u : 3
r : 2
u : 3

Deleting an Element from Counter

To delete an element from Counter you can make use of del , as shown in the example below:

Example:

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2}
del dict1["x"]
print(Counter(dict1))

Output:

Counter({'y': 2, 'z': 2})

Arithmetic operation on Python Counter

Arithmetic operation like addition, subtraction, intersection and union can be done on a Counter as shown in the example below:

Example:

from collections import Counter
counter1 =  Counter({'x': 4, 'y': 2, 'z': -2})

counter2 = Counter({'x1': -12, 'y': 5, 'z':4 })

#Addition
counter3 = counter1 + counter2 # only the values that are positive will be returned.

print(counter3)

#Subtraction
counter4 = counter1 - counter2 # all -ve numbers are excluded.For example z will be z = -2-4=-6, since it is -ve value it is not shown in the output

print(counter4)

#Intersection
counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2

print(counter5)

#Union
counter6 = counter1 | counter2 # it will give positive max values from counter1 and counter2

print(counter6)

Output:

Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})

Methods Available on Python Counter

There are some important methods available with Counter, here is the list of same:

  • elements() : This method will return you all the elements with count >0. Elements with 0 or -1 count will not be returned.
  • most_common(value): This method will return you the most common elements from Counter list.
  • subtract(): This method is used to deduct the elements from another Counter.
  • update(): This method is used to update the elements from another Counter.

Example : elements()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 2, 'z': -2, 'x1':0})

_elements = counter1.elements() # will give you all elements with positive value and count>0
for a in _elements:
    print(a)

Output:

x
x
x
x
x
y
y

Example: most_common(value)

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

common_element = counter1.most_common(2) # The dictionary will be sorted as per the most common element first followed by next.
print(common_element)

common_element1 = counter1.most_common() # if the value is not given to most_common , it will sort the dictionary and give the most common elements from the start.The last element will be the least common element.
print(common_element1)

Output:

 [('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]

Example:subtract()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})

counter1.subtract(counter2)
print(counter1)

Output:

Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})

Example:update()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.update(counter2)
print(counter1)

Output:

Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})

Reassigning Counts in Python

You can re-assign counts of Counter as shown below:

Consider you have a dictionary as : {'x': 5, 'y': 12, 'z': -2, 'x1':0}

You can change the count of the element as shown below:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

counter1['y'] = 20

print(counter1)

Output: After executing you will see that y count is changed from 12 to 20

Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})

Get and set the count of Elements using Counter

To get the count of an element using Counter you can do as follows:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
print(counter1['y']) # this will give you the count of element 'y'

Output:

12

To set the count of the element you can do as follows:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

print(counter1['y'])

counter1['y'] = 20
counter1['y1'] = 10

print(counter1)

Output:

12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})

Summary:

  • Counter is a container that will hold the count of each of the elements present in the container.
  • 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 hashtable object.
  • The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.
  • It allows you to count the items in an iterable list.
  • Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.
  • A Counter can also count elements from another counter.
  • The important methods available on a Counter are elements() , most_common(value), subtract() and update().
  • A counter can be used on a string, list, dictionary, and tuple.

 

YOU MIGHT LIKE: