Looking for Python counter or counter in Python?
Python counter data structure helps us keep track of how many times a distinct item occurs in a Py collection. In this tutorial, you will learn how to use the python counter data structure.
Python Counter class
The Counter
class is derived from the dictionary class. It stores each distinct item of the collection as the key, and the item counts as the value. Similarly, other programming languages use a similar data structure called Bags, or Multisets.
In the following sections, you will learn how to
- Create a
Counter
object - Do arithmetic and set operations between
Counter
objects - Access information about items in a
Counter
- Update the count of one or more items in a
Counter
object - Finally, remove items from a
Counter
object
Creating Counter in Python
To create a counter in python, Firstly, we need to import the Counter
class from the collections
module. After that, we can create Counter
objects by calling the Counter
constructor. Finally, to create an empty Counter
, you must call the constructor without arguments.
from collections import Counter
tally = Counter()
Most importantly to initialize the Counter
object with particular items having zero count, we have to specify the item using a dictionary.
from collections import Counter
tally = Counter({'goats': 0, 'cows': 0, 'sheep': 0})
We use a dictionary to initialize a Counter
when we know the initial items and their quantities. The next example illustrates this.
from collections import Counter
fruit_basket = Counter({'oranges': 2, 'apples': 3})
The variable fruit_basket
is initialized with 2 oranges
and 3 apples
. Another way of initializing a Counter
with known values and counts is by using Keyword Arguments. The following python counter example also creates a Counter
initialized with 2 oranges
and 3 apples
, but this time it uses keyword arguments instead of a dictionary.
from collections import Counter
fruit_basket = Counter(oranges=2, apples=3)
Moreover, we can also create Counter
objects from strings and lists. For strings, the constructor creates a Counter
containing information about how many times each distinct character is found in the string.
from collections import Counter
char_frequency = Counter('free the referee')
print(char_frequency)
Output:
Counter({'e': 7, 'r': 3, 'f': 2, ' ': 2, 't': 1, 'h': 1})
To create a Counter
object with a list, pass the list as an argument to the constructor. The python counter example below creates a Counter
from a dataset of whole numbers.
from collections import Counter
frequency_table = Counter([0, 2, 4, 0, 1, 2, 3, 2, 1, 0, 4, 3, 4, 1, 3, 3, 2])
print(frequency_table)
Output:
Counter({2: 4, 3: 4, 0: 3, 4: 3, 1: 3})
We can see from the output that:
- 2 occurs 4 times
- 3 occurs 4 times
- 0 occurs 3 times
- 4 occurs 3 times
- 1 occurs 3 times
Arithmetic and Set Operations with Python Counters
Counter
provides operations for combining Counter
objects into a new Counter
object. The operations remove any results that have zero or negative counts.
The operations and their results are as follows:
- Addition: Adds the counts of equivalent values
- Subtraction: Carries out subtraction of the counts of equivalent values
- Negation: Negates each count
- Set Union: Takes the maximum count of equivalent values
- Set Intersection: Takes the minimum count of equivalent values
from collections import Counter
# create two new counter objects
x = Counter([2, 2, 2, 3, 3, 3, 3, 5])
y = Counter([2, 2, 3, 3, 5, 5, 5, 5])
# display them
print(f"{x = }")
print(f"{y = }")
# Add two counters
print(f"{x + y = }")
# Subtraction
print(f"{x - y = }")
# Negation
print(f"{- x = }")
# Union of two Counters
print(f"{x | y = }")
# Intersection of two counters
print(f"{x & y = }")
Output:
x = Counter({3: 4, 2: 3, 5: 1})
y = Counter({5: 4, 2: 2, 3: 2})
x + y = Counter({3: 6, 2: 5, 5: 5})
x - y = Counter({3: 2, 2: 1})
- x = Counter()
x | y = Counter({3: 4, 5: 4, 2: 3})
x & y = Counter({2: 2, 3: 2, 5: 1})
The Negation operation produced zero or negative counts, so all the items in the result were dropped, causing the operation to return an empty Counter
.
Accessing a Python Counter
Few ways to access a python counter are-
Get the count of a particular item
We can get the frequency of a particular value in a Counter
by accessing the Counter
using the value as a key
from collections import Counter
frequency_table = Counter([12, 8, 11, 5, 12, 5, 5, 12, 8, 8, 12, 11])
# get the number of times 12 appears in the table
print(f"12 occurs {frequency_table[12]} times")
Output:
12 occurs 4 times
If the key did not exist, our attempt to access the non-existent item would not return a KeyError
, instead, it would return a zero count.
Get the Items in a Python Counter
The Counter.elements()
method returns an iterator object for all the items in the Counter
.
from collections import Counter
char_count = Counter({'a':3, 'b':2, 'c':1})
# get an iterator for the Counter
iter = char_count.elements()
# list out the elements
print(list(iter))
Output:
['a', 'a', 'a', 'b', 'b', 'c']
The output shows what we are expecting: three ‘a’s, two ‘b’s, and one ‘c’.
Get the Most Common Values in a Python Counter
Another information we might need from a Counter
is the values with the highest counts. The method to call is most_common()
, which returns a list of tuples of the form (value, count)
. The items in the list appear in descending order of count.
from collections import Counter
tally = Counter([12, 8, 11, 5, 12, 5, 5, 12, 8, 8, 12, 11])
# return the most common value
print(tally.most_common(1))
# return the 2 most frequent items
print(tally.most_common(2))
# when no arguments are given, all items are returned
print(tally.most_common())
# when None is given as an argument, all items are returned
print(tally.most_common(None))
# when the argument is greater or equal to the number
# of distinct elements, all items are returned
print(tally.most_common(7))
Output:
[(12, 4)]
[(12, 4), (8, 3)]
[(12, 4), (8, 3), (5, 3), (11, 2)]
[(12, 4), (8, 3), (5, 3), (11, 2)]
[(12, 4), (8, 3), (5, 3), (11, 2)]
Update a Counter Object in Python
We can modify, or update, a Counter
by either calling the update()
method, or by reassigning the count of a particular value in the Counter
Using the update() method
We can use the update()
method to add new items to the Counter
.
# create an empty shopping bag
bag = Counter()
# add some items to the shopping bag using update()
bag.update({'pies':3, 'DVDs': 2, 'sodas': 1, 'detergents':1})
# display the shopping bag
print(bag)
# need to add more stuff to the shopping bag
bag.update({'DVDs':2, 'pies':1, 'sodas':2, 'diapers':2})
# display the shopping bag
print(bag)
Output:
Counter({'pies': 3, 'DVDs': 2, 'sodas': 1, 'detergents': 1})
Counter({'pies': 4, 'DVDs': 4, 'sodas': 3, 'diapers': 2, 'detergents': 1})
The second call to update()
added more 'pies'
, 'DVDs'
, and 'sodas'
to the shopping bag. Since there were no 'diapers'
in the bag initially, the second call to update()
added 'diapers'
to the bag.
The previous example strictly used a dictionary for the two update attempts. In addition, It is also possible to vary the kind of data structure passed to the update()
method.
# create an empty Counter
char_freq = Counter()
# first call update() with string argument
char_freq = Counter("eleven")
# display
print(char_freq)
# then, call update() with list argument
char_freq.update(['e', 'l', 'v', 'e', 's'])
# display
print(char_freq)
Output:
Counter({'e': 3, 'l': 1, 'v': 1, 'n': 1})
Counter({'e': 5, 'l': 2, 'v': 2, 'n': 1, 's': 1})
Reassigning the count of an item
The next python counter example shows how to directly set the count of a particular value in a Counter
. Here, we want to take a tally of the number of multiples of certain primes
from collections import Counter
# initialize the tally table
multiples_tally_table = Counter({'multiples of 2':0, 'multiples of 3':0, 'multiples of 5':0})
# count multiples of 2, 3, and 5 from 1 to 20
for num in range(1, 21):
if (num % 2 == 0):
multiples_tally_table['multiples of 2'] += 1
if (num % 3 == 0):
multiples_tally_table['multiples of 3'] += 1
if (num % 5 == 0):
multiples_tally_table['multiples of 5'] += 1
# display the tally table
print(multiples_tally_table)
Output:
Counter({'multiples of 2': 10, 'multiples of 3': 6, 'multiples of 5': 4})
The python increment counter example carries out the re-assignment in the for-loop. When num
satisfies a condition, the program increments the count of an item, so that we can keep track of the number of multiples encountered.
Removing Items from Python Counter
To remove an item from the Counter
, call the pop()
method and pass the value to be removed as an argument. pop()
removes the value and returns the count.
from collections import Counter
x = Counter([2, 2, 2, 3, 3, 3, 3, 5])
print(x)
value = 3
print(f"{x.pop(value)} occurrences of {value} have been removed")
print(x)
Output:
Counter({3: 4, 2: 3, 5: 1})
4 occurrences of 3 have been removed
Counter({2: 3, 5: 1})
Conclusion
To sum up, This wraps up our tutorial on Counter
in Python. We hope the examples in this article are helpful in your python programs!
You can also learn about Self in Python. Or if you are someone who is struggling with the python program and need python homework help them letstacle.com is the best place to hire an expert.