What are counters in Python?

Key takeaways:

  • The collections.Counter class is a part of the collections module and is used to efficiently count the frequency of elements in containers such as lists, dictionaries, tuples, or strings. The output is a dictionary-like object where the keys are the items, and the values are their counts.

  • Counters are mutable and support various operations, such as updating counts with Counter.update, accessing specific counts with square brackets, getting the most common elements using most_common(), clearing counts with clear(), and performing arithmetic or set operations on two counters.

  • Counters can be initialized using any iterable or container, and they offer additional functionalities like reassigning counts and handling negative or zero counts through arithmetic operations like addition and subtraction.

The collections module has container data types (beyond the built-in types list, dictionary, and tuple) and contains many useful data structures for storing information in memory. The counter keeps count of the number of items in the container.

Syntax

To use counters, follow the steps below:

  1. Import counters from the 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 the item.
svg viewer

Initialize a counter

The following code explains how counters can be initialized using lists, tuples, dictionaries, and strings. In the case of strings, the counter gives the frequency of every literal in the string, whereas, in the 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 Counter.update statement. 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(1))

Reassign the count of an item

As 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 counter.clear() method. 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 the operators + and -, they do not give output if the value is negative. So, we use the built-in functions update and subtract to add and subtract the values.

The following code shows how it can be done:

from collections import Counter
# Define two lists
list1 = [1, 2, 3, 4, 2, 2, 1, 1, 1]
list2 = [1, 2, 3, 4, 4, 5, 9, 8, 3]
# Create Counter instances
c1 = Counter(list1)
c2 = Counter(list2)
# Print the original Counters
print("c1:", c1)
print("c2:", c2)
# Add two Counters (using update, which adds counts from c2 to c1)
c1.update(c2) # Adds counts from c2 to c1
print("Add two counters:", c1)
c1 = Counter(list1)
# Subtract c2 from c1 (modifies c1 in-place using subtract)
c1.subtract(c2) # Subtract counts of c2 from c1 (modifies c1 in-place)
print("Subtract two counters:", c1)
# Reset c1 to its original value (for a fresh intersection)
c1 = Counter(list1)
# Find the intersection of c1 and c2 (using the & operator, which takes the minimum counts)
c_intersection = c1 & c2 # Takes the minimum of counts for shared elements
print("Intersection of c1 & c2:", c_intersection)

Ready to write cleaner, more maintainable code? Clean Code in Python guides you through Python fundamentals and advanced techniques, empowering you to confidently create high-quality software.

Conclusion

In Python, the collections.Counter class is a powerful and versatile tool for efficiently counting the frequency of elements in various data structures like lists, tuples, dictionaries, and strings. It simplifies the process of tracking occurrences, offering several built-in methods such as update(), most_common(), and clear() to manage and manipulate counts. Counters are mutable, allowing for easy updates, reassignments, and supporting arithmetic and set operations.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What are counters in coding?

Counters are tools used in programming to keep track of the frequency or occurrence of elements in a collection, such as strings, lists, or dictionaries. In Python, the collections.Counter class is commonly used to count elements efficiently.


What is a program counter in Python?

A program counter is a concept in programming that keeps track of the next instruction to be executed in a program. While Python itself does not expose the program counter directly, it is managed internally by the Python interpreter to execute code sequentially or based on control flow.


What is the difference between count and Counter in Python?

The count method is used to find the number of occurrences of a specific element in a list or string. It is a simple method applied directly on an object. In contrast, Counter is a class from the [collections module[(https://www.educative.io/answers/what-is-the-python-collections-module) that counts occurrences of all elements in an iterable and returns a dictionary-like object with elements as keys and their counts as values.


Which data type is a counter?

A counter is typically represented by an integer data type. Integers are whole numbers (positive, negative, or zero) and are well-suited for tracking counts due to their ability to efficiently store and increment numerical values.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved