Python | Counter Objects | elements()
Last Updated :
25 Jul, 2024
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.
Python | Counter Objects | elements() – FAQs
How to Use the elements() Method in Python Counter?
The elements() method in Python’s Counter class returns an iterator over elements repeating each as many times as its count. Elements with counts less than one are not included. This can be useful for expanding a compact representation of a dataset into its full form.
Example:
from collections import Counter
counter = Counter(a=3, b=2, c=1)
elements = list(counter.elements())
print(elements) # Output: ['a', 'a', 'a', 'b', 'b', 'c']
How to Count Items in an Iterable Using Python Counter?
The Counter class from the collections module can count the occurrences of each item in an iterable, such as a list or a string. When you pass an iterable to Counter, it returns a dictionary-like object where the keys are the items from the iterable and the values are their counts.
Example:
from collections import Counter
items = ['apple', 'banana', 'apple', 'orange', 'banana']
counter = Counter(items)
print(counter) # Output: Counter({'apple': 2, 'banana': 2, 'orange': 1})
Can Counter Handle Negative Counts in Python?
Yes, Counter can handle negative counts. This feature allows you to perform arithmetic operations on Counter objects, such as subtraction, and can result in negative counts. However, elements with a negative count are still part of the Counter object.
Example:
from collections import Counter
counter = Counter(a=3, b=-2, c=1)
print(counter) # Output: Counter({'a': 3, 'c': 1, 'b': -2})
How to Combine Counters in Python?
You can combine Counter objects using arithmetic operations like addition, subtraction, and the update() method. These operations allow you to aggregate counts, find differences, or update counts based on another Counter object.
Using Addition:
Example:
from collections import Counter
counter1 = Counter(a=3, b=2)
counter2 = Counter(a=1, b=2, c=3)
combined = counter1 + counter2
print(combined) # Output: Counter({'a': 4, 'b': 4, 'c': 3})
Using Subtraction:
Example:
from collections import Counter
counter1 = Counter(a=3, b=2)
counter2 = Counter(a=1, b=2, c=3)
difference = counter1 - counter2
print(difference) # Output: Counter({'a': 2})
Using update() Method:
The update() method adds counts from another Counter object or iterable.
Example:
from collections import Counter
counter1 = Counter(a=3, b=2)
counter2 = Counter(a=1, b=2, c=3)
counter1.update(counter2)
print(counter1) # Output: Counter({'a': 4, 'b': 4, 'c': 3})
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 provi
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.
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: # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defin
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
An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python. OrderedDict vs dict in Python`OrderedDict` maintains the sequence in which keys are added, ensuring
10 min read
Defaultdict in Python
Python Defaultdict is a container-like dictionaries present in the module collections. It is a sub-class of the dictionary class that returns a dictionary-like object. The difference from dictionary is, It provides a default value for the key that does not exist and never raises a KeyError. [GFGTABS
5 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: C/C++ Code # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks Worl
2 min read