Counter is used to keeps track of how many times equivalent values are added. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

Syntax

To create a counter, use below syntax

collections.Counter([iterable-or-mapping])

It returns counter object. A Counter is a dict subclass for counting hashable objects. Counts can be any integer value including zero or negative counts.

Below example shows different ways of creating counter.

# Empty counter
c = Counter()

# Counter from an iterable
c = Counter('python')
print(c)

# Output
# Counter({'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1})

# Counter from a mapping
c = Counter({'red': 4, 'blue': 2})
print(c)

# Output
# Counter({'red': 4, 'blue': 2})

# Counter from keyword args
c = Counter(cats=4, dogs=8)
print(c)

# Output
# Counter({'dogs': 8, 'cats': 4})

Important Methods

Counter supports all the methods supported by dictionary. Additional methods supported by Counter objects are

  • elements() : Return an iterator over elements repeating each as many times as its count. If an element’s count is less than one, elements() will ignore it.
  • most_common([n]) : Return a list of the n most common elements and their counts from the most common to the least. If n is omitted, most_common() returns all elements in the counter. Elements with equal counts are ordered in the order first encountered.
  • subtract([iterable-or-mapping]) : Elements are subtracted from an iterable or from another mapping (or counter). Both inputs and outputs may be zero or negative.
  • update([iterable-or-mapping]) : Elements are counted from an iterable or added-in from another mapping (or counter). It adds counts instead of replacing them. Iterable should be a sequence of elements, not a sequence of (key, value) pairs.

Example

Below example shows the illustrate the use of various function supported in Counter. Two counter are created for list of two teams. Then various operation are performed on these counters.

 from collections import Counter

team1 = ["Bob", "James", "Penny", "James", "Frank"]
team2 = ["Bill", "Debbie", "Frank", "James", "Sam"]

# Create a Counter
c1 = Counter(team1)
c2 = Counter(team2)

# Count of player named James
print(c1["James"])

# Output
# 2

# Number of players
print(sum(c1.values()))

# Output
# 5

# Combine the two teams
c1.update(team2)
print(c1)

# Output
# Counter({'James': 3, 'Frank': 2, 'Bob': 1, 'Penny': 1, 'Bill': 1, 'Debbie': 1, 'Sam': 1})

# Most common name in the two teams
print(c1.most_common(3))

# Output
# [('James', 3), ('Frank', 2), ('Bob', 1)]


c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)

c.subtract(d)
print(c)

# Output
# Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

Arithmetic

Counter support arithmetic and set operations. Below example shows the usage of these operators on counter instance. Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

from collections import Counter


c = Counter(a=4, b=2, c=0, d=-2, e = 4)
d = Counter(a=1, b=2, c=3, d=4, f = 3)

# Combined count
print(c + d)

# Output
# Counter({'a': 5, 'b': 4, 'e': 4, 'c': 3, 'f': 3, 'd': 2})

# Substracted count
print(c - d)

# Output
# Counter({'e': 4, 'a': 3})

# Intersection (positive minimums)
print(c & d)

# Output
# Counter({'b': 2, 'a': 1})

# Union (taking maximums)
print(c | d)

# Output
# Counter({'a': 4, 'd': 4, 'e': 4, 'c': 3, 'f': 3, 'b': 2})