Counters in Python | Set 1 (Initialization and Updation) - GeeksforGeeks

03 Mar, 2022
Counter is a container included in the collections module. Now you all must be wondering what is a container. Don’t worry first let’s discuss about the container.  
Containers are objects that hold objects. They provide a way to access the contained objects and iterate over them. Examples of built in containers are Tuple, list, and dictionary. Others are included in Collections module.A Counter is a subclass of dict. Therefore it is an unordered collection where elements and their respective count are stored as a dictionary. This is equivalent to a bag or multiset of other languages.Syntax :  
class collections.Counter([iterable-or-mapping])
Initialization : The constructor of counter can be called in any one of the following ways :  
With sequence of items
 
With dictionary containing keys and counts
 
With keyword arguments mapping string names to counts
Example of each type of initialization :  
Python3
# A Python program to show different ways to create# Counterfrom collections import Counter # With sequence of itemsprint(Counter(['B','B','A','B','C','A','B','B','A','C'])) # with dictionaryprint(Counter({'A':3, 'B':5, 'C':2})) # with keyword argumentsprint(Counter(A=3, B=5, C=2))
Output of all the three lines is same :  
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Updation : We can also create an empty counter in the following manner :  
coun = collections.Counter()
And can be updated via update() method .Syntax for the same :  
coun.update(Data)
 
Python3
# A Python program to demonstrate update()from collections import Countercoun = Counter() coun.update([1, 2, 3, 1, 2, 1, 1, 2])print(coun) coun.update([1, 2, 4])print(coun)
Output :  
Counter({1: 4, 2: 3, 3: 1})
Counter({1: 5, 2: 4, 3: 1, 4: 1})
 
Data can be provided in any of the three ways as mentioned in initialization and the counter’s data will be increased not replaced.
Counts can be zero and negative also.  
Python3
# Python program to demonstrate that counts in# Counter can be 0 and negativefrom collections import Counter c1 = Counter(A=4,  B=3, C=10)c2 = Counter(A=10, B=3, C=4) c1.subtract(c2)print(c1)
Output : 
 Counter({'c': 6, 'B': 0, 'A': -6})
 
We can use Counter to count distinct elements of a list or other collections.  
Python3
# An example program where different list items are# counted using counterfrom collections import Counter # Create a listz = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] # Count distinct elements and print Counter aobjectprint(Counter(z))
Output:  
Counter({'blue': 3, 'red': 2, 'yellow': 1})
 
YouTubeGeeksforGeeks500K subscribersPython Programming Tutorial | Counters in Python - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:17•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3qdRTlWpdGo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
surinderdawra388
Python collections-module
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
C++ Classes and Objects