elements() method of counter in Python

elements() returns an iterator over the elements of the counter object. Iterator will return each element n times as per the count of each element producing the Multiset.

Counter Updated 22 Mar 2017 1 min read

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

python
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

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

red

red

red

red

red

blue

blue

blue

green

green

green

green