Operations on Python Counter
Last Updated :
18 Dec, 2021
The counter can be used to calculate the frequency in a list or in a string because as any list or string is passed as input, it returns output as a dictionary having keys are the unique elements of the list and values are the corresponding frequencies of the elements.
In the code given below, Counter from Collection Python library is imported to find the frequency of every unique character occurring in this string, By using Counter on the list, the frequency of each unique elements present in the list can also be found.
Python3
# Write Python3 code here
# Counter used in string to find frequencies of all its unique Characters
from collections import Counter
s1 ='aabbbcccdeff'
c1 = Counter(s1)
print("c1 :", c1)
# Counter used in List to find frequencies of all its unique elements of list
L1 =[1, 2, 1, 1, 4, 4, 4, 5, 6, 6, 3, 3, 0, 0]
t1 = Counter(L1)
print("t1 :", t1)
Output: c1 : Counter({'b': 3, 'c': 3, 'a': 2, 'f': 2, 'e': 1, 'd': 1})
t1 : Counter({1: 3, 4: 3, 0: 2, 3: 2, 6: 2, 2: 1, 5: 1})
Performing certain operations on returned output dictionary if d is output dictionary then like d.items(), d.keys(), d.values()
Python3
from collections import Counter
d ='aabbbcccdeff'
d = Counter(d)
# To print Counter value
print("d :", d)
# To access the values corresponds to each keys of the returned dictionary
print("d.values() : ", d.values())
# To get the keys and values both of dictionary
print("d.items() :", d.items())
# To get only the keys
print("d.keys() :", d.keys())
# To sort the values of dictionary
print("sorted(d) :", sorted(d))
Output: d : Counter({'b': 3, 'c': 3, 'a': 2, 'f': 2, 'e': 1, 'd': 1})
d.values() : dict_values([2, 3, 3, 2, 1, 1])
d.items() : dict_items([('a', 2), ('b', 3), ('c', 3), ('f', 2), ('e', 1), ('d', 1)])
d.keys() : dict_keys(['a', 'b', 'c', 'f', 'e', 'd'])
sorted(d) : ['a', 'b', 'c', 'd', 'e', 'f']
Addition of two Counters
Addition of two counter creates the additions of values corresponds to each keys, and if a key that is present in one counter and not in other, in that case this key value also get into final output.
Python3
from collections import Counter
t1 = Counter('aabbddffggjik')
t2 = Counter('aaabbbssshhhggdkkll')
print("t1:", t1)
print("t2:", t2)
print("t1 + t2 :", t1 + t2)
Output: t1: Counter({'g': 2, 'a': 2, 'b': 2, 'f': 2, 'd': 2, 'k': 1, 'j': 1, 'i': 1})
t2: Counter({'a': 3, 'b': 3, 'h': 3, 's': 3, 'l': 2, 'g': 2, 'k': 2, 'd': 1})
t1+t2 : Counter({'a': 5, 'b': 5, 'g': 4, 'k': 3, 'h': 3, 'd': 3, 's': 3, 'l': 2, 'f': 2, 'j': 1, 'i': 1})
Subtraction of two Counters
Counts of common elements are subtracted from each other and (keeps only positive counts)
Python3
from collections import Counter
t1 = Counter('aabbddffggjik')
t2 = Counter('aaabbbssshhhggdkkll')
print("t1:", t1)
print("t2:", t2)
print("t1-t2 :", t1-t2)
print("t2-t1 :", t2-t1)
Output: t1: Counter({'f': 2, 'd': 2, 'b': 2, 'a': 2, 'g': 2, 'k': 1, 'i': 1, 'j': 1})
t2: Counter({'h': 3, 'b': 3, 'a': 3, 's': 3, 'l': 2, 'k': 2, 'g': 2, 'd': 1})
t1-t2 : Counter({'f': 2, 'i': 1, 'j': 1, 'd': 1})
t2-t1 : Counter({'h': 3, 's': 3, 'l': 2, 'k': 1, 'b': 1, 'a': 1})
Intersections(&) of two Counters
Intersection(&) will keep only the minimum of corresponding counts: min(t1[x], t2[x]):
Python3
from collections import Counter
t1 = Counter('aaabbbbccdeeee')
t2 = Counter('aabbccccdddee')
print("t1 :", t1)
print("t2 :", t2)
print("t1&t2 :", t1&t2)
Output: t1 : Counter({'e': 4, 'b': 4, 'a': 3, 'c': 2, 'd': 1})
t2 : Counter({'c': 4, 'd': 3, 'a': 2, 'e': 2, 'b': 2})
t1&t2 : Counter({'c': 2, 'a': 2, 'e': 2, 'b': 2, 'd': 1})
Union(|) of two Counters
Union(|) will keep only the maximum of corresponding counts: max(c[x], d[x]):
Python3
from collections import Counter
t1 = Counter('aaabbbbccdeeee')
t2 = Counter('aabbccccdddee')
print("t1 :", t1)
print("t2 :", t2)
print("t1|t2 :", t1|t2)
Output: t1 : Counter({'b': 4, 'e': 4, 'a': 3, 'c': 2, 'd': 1})
t2 : Counter({'c': 4, 'd': 3, 'a': 2, 'b': 2, 'e': 2})
t1|t2 : Counter({'b': 4, 'e': 4, 'c': 4, 'a': 3, 'd': 3})
Similar Reads
Map Reduce and Filter Operations in Python
In this article, we will study Map, Reduce, and Filter Operations in Python. These three operations are paradigms of functional programming. They allow one to write simpler, shorter code without needing to bother about intricacies like loops and branching. In this article, we will see Map Reduce and
3 min read
Python - Operation to each element in list
Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
2 min read
Python | Alternate Rear iteration
The iteration of numbers is done by looping techniques in python. There are many techniques in Python which facilitate looping. Sometimes we require to perform the looping backwards in alternate way and having shorthands to do so can be quite useful. Letâs discuss certain ways in which this can be d
3 min read
Python List Counting Programs
Python provides various methods, such as count(), dictionary-based counting, and list comprehensions, to efficiently handle counting operations. This collection of Python programs covers different ways to count elements in lists, including counting occurrences, matching elements, frequency analysis,
2 min read
Python - Count Dictionary Items
In Python, dictionaries are one of the most widely used data structures. They allow us to store data in key-value pairs where each key maps to a value. In this article, weâll explore how to count dictionary items in Python using different methods including built-in functions and loops.Counting Total
3 min read
Python Tuple count() Method
In this article, we will learn about the count() method used for tuples in Python. The count() method of a Tuple returns the number of times the given element appears in the tuple. Example Python3 tuple = (1, 2, 3, 1, 2, 3, 1, 2, 3) print(tuple.count(3)) Output : 3Python Tuple count() Method Syntax
3 min read
Python - Matrix elements Frequencies Counter
Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using Counter() + sum() + map() The
5 min read
Python | Case Counter in String
Sometimes, while working with Python String, we can have a problem in which we need to separate the lower and upper case count. This kind of operation can have its application in many domains. Let's discuss certain ways in which this task can be done. Method #1: Using map() + sum() + isupper() + isl
7 min read
Python Fundamentals Coding Practice Problems
Welcome to this article on Python basic problems, featuring essential exercises on coding, number swapping, type conversion, conditional statements, loops and more. These problems help beginners build a strong foundation in Python fundamentals and problem-solving skills. Letâs start coding!Python Ba
1 min read
Python | Custom length Matrix
Sometimes, we need to initialize a matrix in Python of variable length from the list containing elements. In this article, we will discuss the variable length method initialization and certain shorthands to do so. Let's discuss certain ways to perform this. Method #1: Using zip() + list comprehensio
6 min read