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:
OrderedDict in Python
Next article icon

Python | Counter Objects | elements()

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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-class that is used to count hashable objects. It implicitly creates a hash table of an iterable when invoked.

elements() is one of the functions of Counter class, when invoked on the Counter object will return an itertool of all the known elements in the Counter object.

Parameters : Doesn't take any parameters
Return type : Returns an itertool for all the elements with positive count in the Counter object
Errors and Exceptions : 
-> It will print garbage value when directly printed because it returns an itertool, not a specific data-container. 
-> If the count of an item is already initialized in Counter object, then it will ignore the ones with zero and negative values. 
 

Code #1: Working of elements() on a simple data container  

Python3
# import counter class from collections module from collections import Counter  # Creation of a Counter Class object using  # string as an iterable data container x = Counter("geeksforgeeks")  # printing the elements of counter object for i in x.elements():     print ( i, end = " ") 

Output: 

g g e e e e k k s s f o r 

We can also create Counter class object using a list as an iterable data container.

Python
# import counter class from collections module from collections import Counter  #Creating a Counter class object using list as an iterable data container a = [12, 3, 4, 3, 5, 11, 12, 6, 7]  x = Counter(a)  #directly printing whole x print(x)  #We can also use .keys() and .values() methods to access Counter class object for i in x.keys():       print(i, ":", x[i])      #We can also make a list of keys and values of x x_keys = list(x.keys()) x_values = list(x.values())  print(x_keys) print(x_values) 

Output:

Counter({12: 2, 3: 2, 4: 1, 5: 1, 11: 1, 6: 1, 7: 1})
12 : 2
3 : 2
4 : 1
5 : 1
11 : 1
6 : 1
7 : 1
[12, 3, 4, 5, 11, 6, 7]
[2, 2, 1, 1, 1, 1, 1]


Code #2: Elements on a variety of Counter Objects with different data-containers  

Python3
# import counter class from collections module from collections import Counter  # Creation of a Counter Class object using  # a string as an iterable data container # Example - 1 a = Counter("geeksforgeeks")  # Elements of counter object for i in a.elements():     print ( i, end = " ") print()      # Example - 2 b = Counter({'geeks' : 4, 'for' : 1,              'gfg' : 2, 'python' : 3})  for i in b.elements():     print ( i, end = " ") print()  # Example - 3 c = Counter([1, 2, 21, 12, 2, 44, 5,               13, 15, 5, 19, 21, 5])  for i in c.elements():     print ( i, end = " ") print()                              # Example - 4 d = Counter( a = 2, b = 3, c = 6, d = 1, e = 5)  for i in d.elements():     print ( i, end = " ") 

Output:

g g e e e e k k s s f o r 
geeks geeks geeks geeks for gfg gfg python python python
1 2 2 21 21 12 44 5 5 5 13 15 19
a a b b b c c c c c c d e e e e e


Code #3: To demonstrate what elements() return when it is printed directly  

Python3
# import Counter from collections from collections import Counter  # creating a raw data-set x = Counter ("geeksforgeeks")  # will return a itertools chain object # which is basically a pseudo iterable container whose # elements can be used when called with a iterable tool print(x.elements()) 

Output: 

itertools.chain object at 0x037209F0


Code #4: When the count of an item in Counter is initialized with negative values or zero.  

Python3
# import Counter from collections from collections import Counter  # creating a raw data-set using keyword arguments x = Counter (a = 2, x = 3, b = 3, z = 1, y = 5, c = 0, d = -3)  # printing out the elements for i in x.elements():     print( "% s : % s" % (i, x[i]), end ="\n") 

Output: 

a : 2
a : 2
x : 3
x : 3
x : 3
b : 3
b : 3
b : 3
z : 1
y : 5
y : 5
y : 5
y : 5
y : 5


Note: We can infer from the output that items with values less than 1 are omitted by elements().

Applications: 
Counter object along with its functions are used collectively for processing huge amounts of data. We can see that Counter() creates a hash-map for the data container invoked with it which is very useful than by manual processing of elements. It is one of a very high processing and functioning tools and can even function with a wide range of data too.


Next Article
OrderedDict in Python

R

retr0
Improve
Article Tags :
  • Python
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
    Namedtuple in Python
    Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple.What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provid
    8 min read
    Deque in Python
    A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.E
    6 min read
    ChainMap in Python
    Python contains a container called "ChainMap" which encapsulates many dictionaries into one unit. ChainMap is member of module "collections". Example: Python3 # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6}
    3 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
    OrderedDict in Python
    OrderedDict is a subclass of Python's built-in dictionary dict that remembers the order in which keys are inserted. Unlike older versions of Python where dictionaries did not guarantee order, OrderedDict preserves insertion order reliably.Note: From Python 3.7 onwards, the built-in dict also preserv
    7 min read
    Defaultdict in Python
    In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it.Key Features of defaultdict:When we access a key that doesn'
    6 min read
    Collections.UserDict in Python
    An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
    2 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
    Collections.UserString in Python
    Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: Python3 # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World'
    2 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