Wednesday 5 October 2022

Counter Function in Python and Example

 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.


For example see following code :

from collections import Counter
list1 = 'aabbbccde'
print(Counter(list1))


Then Output

Counter({'b': 3, 'a': 2, 'c': 2, 'd': 1, 'e': 1})



Source : https://www.geeksforgeeks.org/python-counter-objects-elements/

No comments:

Post a Comment