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.
Counter.items()
The Counter.items() method helps to see the elements of the list along with their respective frequencies in a tuple.
Syntax : Counter.items()
Paramters : None
Returns : object of class dict_items
Example :
# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instatiating a Counter objectob = Counter(list) # Counter.items()items = ob.items() print("The datatype is " + str(type(items))) # displaying the dict_itemsprint(items) # iterating over the dict_itemsfor i in items: print(i) |
Output :
The datatype is
dict_items([(1, 2), (2, 2), (3, 2), (4, 2), (5, 1), (6, 1), (7, 1), (9, 1), (8, 1)])
(1, 2)
(2, 2)
(3, 2)
(4, 2)
(5, 1)
(6, 1)
(7, 1)
(9, 1)
(8, 1)
Counter.keys()
The Counter.keys() method helps to see the unique elements in the list.
Syntax : Counter.keys()
Paramters : None
Returns : object of class dict_items
Example :
# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instatiating a Counter objectob = Counter(list) # Counter.keys()keys = ob.keys() print("The datatype is " + str(type(keys))) # displaying the dict_itemsprint(keys) # iterating over the dict_itemsfor i in keys: print(i) |
Output :
The datatype is
dict_keys([1, 2, 3, 4, 5, 6, 7, 9, 8])
1
2
3
4
5
6
7
9
8
Counter.values()
The Counter.values() method helps to see the frequencies of each unique element.
Syntax : Counter.values()
Paramters : None
Returns : object of class dict_items
Example :
# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instatiating a Counter objectob = Counter(list) # Counter.values()values = ob.values() print("The datatype is " + str(type(values))) # displaying the dict_itemsprint(values) # iterating over the dict_itemsfor i in values: print(i) |
Output :
The datatype is
dict_values([2, 2, 2, 2, 1, 1, 1, 1, 1])
2
2
2
2
1
1
1
1
1
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


