Elements() Method Of Counter In Python

Method Name:

elements

 

Method Signature:

elements()

 

Method Overview:

  • elements() method returns an iterator for the elements present in the counter.

 

  • Since a Counter object is a set of elements Vs the count of each element, the iterator returned will return each element as many times the count of that element.

 

  • If a count() object is printed directly only the element vs count mapping will be printed. Having the elements() method is essential to see the Multiset present in the Counter object.

iterator method of counter object

Example:

import collections

 

counter = collections.Counter()

 

counter["red"]      = 5 

counter["blue"]     = 3 

counter["green"]    = 4

 

("Printing the counter object:")

print(counter) 

 

itr = counter.elements()

 

# print the items of the iterator received through elements()

for item in itr:

    print(item)

 

Output:

Counter({'red': 5, 'green': 4, 'blue': 3})

red

red

red

red

red

blue

blue

blue

green

green

green

green

 

 


Copyright 2023 © pythontic.com