What are counters in Python?

The collections module has container datatypes (beyond the built-in types list, dictionary, and tuple) and contains many useful data structures that you can use to store information in memory. The counter keeps the count of the number of items in the container.

Syntax

For using counters, follow the steps below:

  1. Import counters from collection module

    • from collections import Counter
  2. Make an instance of the counter

    • c = Counter(x)
    • Where x can be a list, dictionary, array, tuple or any other data structure available in Python.
  3. Print output

    • The output will be just like a dictionary i.e. the keys will be the item and the value will be the frequency of item.
svg viewer

Initialize a counter

The following code explains how counters can be initialized using lists, tuples, dictionary, and strings. In the case of strings, the counter gives the frequency of every literal in the string whereas in case of a list, tuple, and dictionary it gives the occurrence of each item in the respective container.

from collections import Counter
#define a list
list=[1,2,3,4,5,6,7,2,3,2,3]
#make instance of Counter
c=Counter(list)
print("list:",list,"\n")
print(c,"\n")
#define a tuple
tuple = ("apple", "banana", "cherry","orange","apple")
#make instance of Counter
c1=Counter(tuple)
print("\ntuple:",tuple,"\n")
print(c1,"\n")
#define a string
str="Python Programming"
#make instance of Counter
c2=Counter(str)
print ("String:",str,"\n")
print(c2,"\n")
#define a dictionary
dict={'a':3,'b':2,'c':1}
#make instance of Counter
c3=Counter(dict)
print("Dictionary:",dict,"\n")
print(c3,"\n")

Update a counter

An empty counter can be declared and updated using the statement Counter.update. The following code shows how it can be done:

from collections import Counter
#initialize with an empty Counter
c=Counter()
#update Counter
c.update("1")
print (c)
c.update("1")
print(c)

Access a particular item count

To access a particular item count write the counter name and specify the item name enclosed within square brackets. The following code shows how it can be done:

from collections import Counter
# define a list
list=[1,2,3,4,2,2,1,1,1]
# make the instance of Counter
c=Counter(list)
# print the count of item 1 in the list
item=1
print("Item:",c[item])

Get the most frequent element

To get the elements with the highest frequencies i.e., n most common elements, we call the method most_common(). The following code shows how it can be done:

from collections import Counter
# define a list
list=[1,2,3,4,2,2,1,1,1]
# make the instance of Counter
c=Counter(list)
#print the most common element
print("Item:",c.most_common)

Re-assign count of an item

Since python counters are mutable, it is possible to reassign a value to an item.

from collections import Counter
# define a list
list=[1,2,3,4,2,2,1,1,1]
# make the instance of Counter
c=Counter(list)
# reassign the value of 1
c[1]=3
#print the value of counter
print(c)

Clear a counter value

To clear a counter value, call the method of counter counter.clear(). The following code shows how it can be done:

from collections import Counter
# define a list
list=[1,2,3,4,2,2,1,1,1]
# make the instance of Counter
c=Counter(list)
print("Initilially :",c)
# clear the value of counter
c.clear()
#print the value of counter after clearing it
print("clear() :",c)

Arithmetic operations on Counters

All basic arithmetic and set operations can be applied on two counters.

Note: If we use operators +, - . It does not give output if the value is negative. So we use the built-in function add and subtract for adding and subtracting values.

The following code shows how it can be done:

from collections import Counter
# define a list
list1=[1,2,3,4,2,2,1,1,1]
list2=[1,2,3,4,4,5,9,8,3]
# make the instance of Counter
c1=Counter(list1)
c2=Counter(list2)
print("c1:",c1)
print("c2:",c2)
c1.__add__(c2)
print("Add two counter",c1)
c1.subtract(c2)
print("Subtract two counters",c1)
c1&c2
print("Intersection of c1 & c2",c1)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved