Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 len() Function
Next article icon

Python collections Counter

Last Updated : 18 Dec, 2024
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:

Table of Content

  • Syntax for counters
  • Creating a Counter
  • Accessing Counter Elements
  • Updating counters
  • Counter Methods
  • Arithmetic Operations on Counters

Syntax

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

Initialization: 

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

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.

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

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] 

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

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)] 

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}) 

The 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 len() Function
author
kartik
Improve
Article Tags :
  • Python
  • Python collections-module
Practice Tags :
  • python

Similar Reads

  • 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
  • Collections.UserList in Python
    Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
    2 min read
  • Garbage Collection in Python
    Garbage Collection in Python is an automatic process that handles memory allocation and deallocation, ensuring efficient use of memory. Unlike languages such as C or C++ where the programmer must manually allocate and deallocate memory, Python automatically manages memory through two primary strateg
    5 min read
  • Python len() Function
    The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example: [GFGTABS] Python s = "G
    2 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:
    2 min read
  • Python | Operator.countOf
    Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. Syntax : Operator.countOf(freq = a, value = b) Parameters : freq : It can be list or any other data type which store value value : It is value for which we have to count the num
    2 min read
  • numpy.count() in Python
    numpy.core.defchararray.count(arr, substring, start=0, end=None): Counts for the non-overlapping occurrence of sub-string in the specified range. Parameters: arr : array-like or string to be searched. substring : substring to search for. start, end : [int, optional] Range to search in. Returns : An
    1 min read
  • Convert integer to string in Python
    In this article, we’ll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function. Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string. [GFGTABS] Python n = 42
    2 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
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