Open In App

Counters in Python | Set 1 (Initialization and Updation)

Last Updated : 26 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The 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 the container.

What is 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 Tuples, lists, and dictionaries. Others are included in the 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 the counter can be called in any one of the following ways:

  • With a sequence of items
  • With a dictionary containing keys and counts
  • With keyword arguments mapping string names to counts

Initializing a Counter

Python3




# A Python program to show different ways to create
# Counter
from collections import Counter
 
# With sequence of items
print(Counter(['B','B','A','B','C','A','B','B','A','C']))
 
# with dictionary
print(Counter({'A':3, 'B':5, 'C':2}))
 
# with keyword arguments
print(Counter(A=3, B=5, C=2))


Output:

Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})

Updation in counters

We can also create an empty counter in the following manner : 

coun = collections.Counter()

And can be updated via the update() method. The syntax for the same : 

coun.update(Data)

Python3




# A Python program to demonstrate update()
from collections import Counter
coun = 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}

Subtract two Counters

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 or negative also.

Python3




# Python program to demonstrate that counts in
# Counter can be 0 and negative
from 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})

Distinct Count in the list

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 counter
from collections import Counter
 
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
 
# Count distinct elements and print Counter aobject
print(Counter(z))


Output:

Counter({'blue': 3, 'red': 2, 'yellow': 1})

Printing Counter Values

We can also access all the keys and values of a counter using the keys(), values(), and items() methods. These methods return views of the keys, values, and key-value pairs in the counter, respectively. 

Python3




from collections import Counter
my_counter = Counter('abracadabra')
print(my_counter.keys())
print(my_counter.values())
print(my_counter.items())


Output:

dict_keys(['a', 'b', 'r', 'c', 'd'])
dict_values([5, 2, 2, 1, 1])
dict_items([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)])

If you want to learn more about accessing counters in Python, the article  (Accessing Counters) is a great resource.



Similar Reads

Output of C programs | Set 62 (Declaration & Initialization)
Prerequisite : Declaration & Initialization in C programmingQ1. Consider the following code: C/C++ Code #include <stdio.h> void main() { extern int i; i = 20; printf("%d", sizeof(i)); } What would be the output of the above code? A. 2 B. 4 C. Would vary from compiler to compiler. D. Error. Output: D Error: format '%d' expects ar
3 min read
Python | List Initialization with alternate 0s and 1s
The initialization of a list with a single number is a generic problem whose solution has been dealt with many times. But sometimes we require to initialize the list with elements alternatively repeating K no. of times. This has use cases in M.L. or A. I algorithms that require presetting of data in lists. Let's discuss certain ways in which this p
6 min read
Python - Incremental K sized Row Matrix Initialization
Sometimes, while working with Python, we can have a problem in which we need to perform initialization of matrix with Incremental numbers. This kind of application can come in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing This task can be performed in brute way using loop.
6 min read
Python | Boolean list initialization
Many times in programming, we require to initialize a list with some initial values. In Dynamic programming, this is used more often and mostly the requirement is to initialize with a boolean 0 or 1. Let's discuss certain ways in which this can be achieved. Method #1: Using list comprehension This can easily be done with the naive method, hence, ca
4 min read
Python | Interval Initialization in list
There are numerous ways to initialize the list with the elements, but sometimes, its required to initialize the lists with the numbers in a sliced way. This can be custom and hence knowledge of this can come handy. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + enumerate() The list comprehension can do
5 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Custom dictionary initialization in list
While working with Python, we can have a problem in which we need to initialize a list of a particular size with custom dictionaries. This task has it’s utility in web development to store records. Let’s discuss certain ways in which this task can be performed. Method #1 : Using {dict} + "*" operator This task can be performed using the “*” operato
3 min read
Python - Incremental value initialization in Dictionary
The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index incremental with K difference. Let’s discuss certain ways in which t
5 min read
Python - K Matrix Initialization
Sometimes in the world of competitive programming, we need to initialise the matrix, but we don’t wish to do it in a longer way using a loop. We need a shorthand for this. This type of problem is quite common in dynamic programming domain. Let’s discuss certain ways in which this can be done. Method #1: Using List comprehension List comprehension c
5 min read
Python - Incremental Range Initialization in Matrix
Sometimes, while working with Python, we can have a problem in which we need to perform the initialization of Matrix. Simpler initialization is easier. But sometimes, we need to perform range incremental initialization. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is brute way in which this task can be
4 min read