Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Collections Module
Next article icon

Python Collections Counter

Last Updated : 12 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Counters are a subclass of the dict class in Python collections module. They are used to count the occurrences of elements in an iterable or to count the frequency of items in a mapping. Counters provide a clean and efficient way to tally up elements and perform various operations related to counting.

Example:

Python
from collections import Counter  # Example list of elements val = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]  # Creating a Counter ctr = Counter(val)  print(ctr)   

Output
Counter({4: 4, 3: 3, 2: 2, 1: 1}) 

In this example, the Counter counts the occurrences of each element in the list.

Let's take a look at counters in Python in detail:

Syntax

class collections.Counter([iterable-or-mapping])

Parameters: The constructor of the counter can be called in any one of the following ways:

  • With a sequence of items
  • With a dictionary containing keys and counts
  • With keyword arguments mapping string names to counts

Return Type: it returns a "collections.counter" object (functionally its a dictionary-like object)

Creating a Counter

To use a Counter, we first need to import it from the collections module.

Python
from collections import Counter  # Creating a Counter from a list ctr1 = Counter([1, 2, 2, 3, 3, 3])  # Creating a Counter from a dictionary ctr2 = Counter({1: 2, 2: 3, 3: 1})  # Creating a Counter from a string ctr3 = Counter('hello')  print(ctr1) print(ctr2) print(ctr3) 

Output
Counter({3: 3, 2: 2, 1: 1}) Counter({2: 3, 1: 2, 3: 1}) Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1}) 

In these examples, we create Counters from different types of iterables.

Refer to collection module to learn in detail.

Accessing Counter Elements

We can access the count of each element using the element as the key. If an element is not in the Counter, it returns 0.

Example:

Python
from collections import Counter  ctr = Counter([1, 2, 2, 3, 3, 3])  # Accessing count of an element print(ctr[1])   print(ctr[2])   print(ctr[3])   print(ctr[4])  # (element not present) 

Output
1 2 3 0 

This example shows how to access the count of specific elements in the Counter.

Updating counters

Counters can be updated by adding new elements or by updating the counts of existing elements. We can use the update() method to achieve this.

Example:

Python
from collections import Counter  ctr = Counter([1, 2, 2])  # Adding new elements ctr.update([2, 3, 3, 3])  print(ctr)   

Output
Counter({2: 3, 3: 3, 1: 1}) 

Counter Methods

1. elements()

Returns an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order.

Python
from collections import Counter  ctr = Counter([1, 2, 2, 3, 3, 3]) items = list(ctr.elements())  print(items)   

Output
[1, 2, 2, 3, 3, 3] 

Explanation: elements() method returns an iterator that produces all elements in the Counter.

2. most_common()

Returns a list of the n most common elements and their counts from the most common to the least. If n is not specified, it returns all elements in the Counter.

Python
from collections import Counter  ctr = Counter([1, 2, 2, 3, 3, 3]) common = ctr.most_common(2)  print(common)  

Output
[(3, 3), (2, 2)] 

3. subtract()

Subtracts element counts from another iterable or mapping. Counts can go negative.

Python
from collections import Counter  ctr = Counter([1, 2, 2, 3, 3, 3]) ctr.subtract([2, 3, 3])  print(ctr)   

Output
Counter({1: 1, 2: 1, 3: 1}) 

Explanation: subtract() method decreases the counts for elements found in another iterable.

Arithmetic Operations on Counters

Counters support addition, subtraction, intersection union operations, allowing for various arithmetic operations.

Example:

Python
from collections import Counter  ctr1 = Counter([1, 2, 2, 3]) ctr2 = Counter([2, 3, 3, 4])  # Addition print(ctr1 + ctr2)   # Subtraction print(ctr1 - ctr2)    # Intersection print(ctr1 & ctr2)   # Union print(ctr1 | ctr2)   

Output
Counter({2: 3, 3: 3, 1: 1, 4: 1}) Counter({1: 1, 2: 1}) Counter({2: 1, 3: 1}) Counter({2: 2, 3: 2, 1: 1, 4: 1}) 

If you want to learn more about accessing counters in Python, the article  (Accessing Counters) is a great resource.


Next Article
Python Collections Module

K

kartik
Improve
Article Tags :
  • Python
  • Computer Science Fundamentals
  • Python collections-module
Practice Tags :
  • python

Similar Reads

    Python collections Counter
    Counters are a subclass of the dict class in Python collections module. They are used to count the occurrences of elements in an iterable or to count the frequency of items in a mapping. Counters provide a clean and efficient way to tally up elements and perform various operations related to countin
    4 min read
    Python Collections Module
    The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
    13 min read
    Python time.perf_counter_ns() Function
    Python time.perf_counter_ns() function gives the integer value of time in nanoseconds. Syntax: from time import perf_counter_ns We can find the elapsed time by using start and stop functions. We can also find the elapsed time during the whole program by subtracting stoptime and starttime Example 1:
    1 min read
    Python - Itertools.count()
    Python Itertools are a great way of creating complex iterators which helps in getting faster execution time and writing memory-efficient code. Itertools provide us with functions for creating infinite sequences and itertools.count() is one such function and it does exactly what it sounds like, it co
    3 min read
    Numpy count_nonzero method | Python
    numpy.count_nonzero() function counts the number of non-zero values in the array arr. Syntax : numpy.count_nonzero(arr, axis=None) Parameters : arr : [array_like] The array for which to count non-zeros. axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is
    1 min read
    Python | Counter Objects | elements()
    Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences