Counters are tools used in programming to keep track of the frequency or occurrence of elements in a collection, such as strings, lists, or dictionaries. In Python, the collections.Counter
class is commonly used to count elements efficiently.
Key takeaways:
The
collections.Counter
class is a part of thecollections
module and is used to efficiently count the frequency of elements in containers such as lists, dictionaries, tuples, or strings. The output is a dictionary-like object where the keys are the items, and the values are their counts.Counters are mutable and support various operations, such as updating counts with
Counter.update
, accessing specific counts with square brackets, getting the most common elements usingmost_common()
, clearing counts withclear()
, and performing arithmetic or set operations on two counters.Counters can be initialized using any iterable or container, and they offer additional functionalities like reassigning counts and handling negative or zero counts through arithmetic operations like addition and subtraction.
The collections module has container data types (beyond the built-in types list, dictionary, and tuple) and contains many useful data structures for storing information in memory. The counter keeps count of the number of items in the container.
To use counters, follow the steps below:
Import counters from the collection module:
from collections import Counter
Make an instance of the counter:
x
can be a list, dictionary, array, tuple, or any other data structure available in Python.Print output:
The following code explains how counters can be initialized using lists, tuples, dictionaries, and strings. In the case of strings, the counter gives the frequency of every literal in the string, whereas, in the case of a list, tuple, and dictionary, it gives the occurrence of each item in the respective container.
from collections import Counter#define a listlist=[1,2,3,4,5,6,7,2,3,2,3]#make instance of Counterc=Counter(list)print("list:",list,"\n")print(c,"\n")#define a tupletuple = ("apple", "banana", "cherry","orange","apple")#make instance of Counterc1=Counter(tuple)print("\ntuple:",tuple,"\n")print(c1,"\n")#define a stringstr="Python Programming"#make instance of Counterc2=Counter(str)print ("String:",str,"\n")print(c2,"\n")#define a dictionarydict={'a':3,'b':2,'c':1}#make instance of Counterc3=Counter(dict)print("Dictionary:",dict,"\n")print(c3,"\n")
An empty counter can be declared and updated using the Counter.update
statement. The following code shows how it can be done:
from collections import Counter#initialize with an empty Counterc=Counter()#update Counterc.update("1")print (c)c.update("1")print(c)
To access a particular item count, write the counter name and specify the item name enclosed within square brackets. The following code shows how it can be done:
from collections import Counter# define a listlist=[1,2,3,4,2,2,1,1,1]# make the instance of Counterc=Counter(list)# print the count of item 1 in the listitem=1print("Item:",c[item])
To get the elements with the highest frequencies, i.e., n most common elements, we call the method most_common()
. The following code shows how it can be done:
from collections import Counter# define a listlist=[1,2,3,4,2,2,1,1,1]# make the instance of Counterc=Counter(list)#print the most common elementprint("Item:",c.most_common(1))
As python counters are mutable, it is possible to reassign a value to an item.
from collections import Counter# define a listlist=[1,2,3,4,2,2,1,1,1]# make the instance of Counterc=Counter(list)# reassign the value of 1c[1]=3#print the value of counterprint(c)
To clear a counter value, call the counter.clear()
method. The following code shows how it can be done:
from collections import Counter# define a listlist=[1,2,3,4,2,2,1,1,1]# make the instance of Counterc=Counter(list)print("Initilially :",c)# clear the value of counterc.clear()#print the value of counter after clearing itprint("clear() :",c)
All basic arithmetic and set operations can be applied on two counters.
Note: If we use the operators + and -, they do not give output if the value is negative. So, we use the built-in functions
update
andsubtract
to add and subtract the values.
The following code shows how it can be done:
from collections import Counter# Define two listslist1 = [1, 2, 3, 4, 2, 2, 1, 1, 1]list2 = [1, 2, 3, 4, 4, 5, 9, 8, 3]# Create Counter instancesc1 = Counter(list1)c2 = Counter(list2)# Print the original Countersprint("c1:", c1)print("c2:", c2)# Add two Counters (using update, which adds counts from c2 to c1)c1.update(c2) # Adds counts from c2 to c1print("Add two counters:", c1)c1 = Counter(list1)# Subtract c2 from c1 (modifies c1 in-place using subtract)c1.subtract(c2) # Subtract counts of c2 from c1 (modifies c1 in-place)print("Subtract two counters:", c1)# Reset c1 to its original value (for a fresh intersection)c1 = Counter(list1)# Find the intersection of c1 and c2 (using the & operator, which takes the minimum counts)c_intersection = c1 & c2 # Takes the minimum of counts for shared elementsprint("Intersection of c1 & c2:", c_intersection)
Ready to write cleaner, more maintainable code? Clean Code in Python guides you through Python fundamentals and advanced techniques, empowering you to confidently create high-quality software.
In Python, the collections.Counter
class is a powerful and versatile tool for efficiently counting the frequency of elements in various data structures like lists, tuples, dictionaries, and strings. It simplifies the process of tracking occurrences, offering several built-in methods such as update()
, most_common()
, and clear()
to manage and manipulate counts. Counters are mutable, allowing for easy updates, reassignments, and supporting arithmetic and set operations.
Haven’t found what you were looking for? Contact Us
Free Resources