Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Counting Items with collections.Counter

Use collections.Counter to tally items, rank frequent values, update counts, and compare multisets.

Levels: Intermediate ~17 min read

Intermediate

A dictionary is a good choice when a key should map to one current value. Counting is a more specific job: each item may appear many times, and you want to keep its running total. collections.Counter is a dictionary subclass built for tallying hashable items without writing the counting loop yourself.

Build a counter from data

Pass an iterable to Counter to count each hashable item. You can also initialize one from a mapping of items to existing counts. The keys are the distinct items; their values are the counts. Strings are iterables too, so Counter('level') counts characters, not words.

Interactive Runnable example
Edit

Ready to run.

Quick check

What does Counter('cocoa') count?

from collections import Counter
counts = Counter("cocoa")
print(counts['o'])
print(counts['c'])

Looking up a missing key returns 0 rather than raising KeyError. That lookup does not insert the missing key into the counter. This makes it convenient to ask for a count without first checking membership.

Interactive Runnable example
Edit

Ready to run.

Find the most common items

most_common(n) returns up to n (item, count) pairs from highest count to lowest. With equal counts, it preserves the order in which those items were first encountered. Omit n to get all items in that order by count. This method ranks existing counts; it does not change them.

Interactive Runnable example
Edit

Ready to run.

Quick check

What shape does most_common(2) return?

from collections import Counter
counts = Counter("banana")
print(counts.most_common(2))

Add counts and subtract counts

Counter.update() adds counts from an iterable or mapping; unlike dict.update(), a mapping does not replace the old counts. Counter.subtract() subtracts counts but keeps zero and negative results. Setting a count to zero also does not remove that key; use del when you need to remove the entry.

Interactive Runnable example
Edit

Ready to run.

Quick check

How does Counter.update({'apple': 3}) differ from dict.update({'apple': 3})?

from collections import Counter
counts = Counter(apple=2)
counts.update({"apple": 3})
print(counts["apple"])

Expand counts and total them

total() adds the counts together. elements() returns an iterator that repeats each item according to its count, but it ignores zero and negative counts. Because this operation repeats items, counts used with elements() should be integers. It is not the same as iterating over the distinct keys.

Interactive Runnable example
Edit

Ready to run.

Quick check

Which counts are included by elements()?

from collections import Counter
counts = Counter(a=2, b=0, c=-1)
print(list(counts.elements()))

Combine counters as multisets

Counter supports multiset-style operations. Addition combines counts, subtraction keeps only positive differences, intersection (&) keeps the smaller count for each item, and union (|) keeps the larger count. These operators discard results that are zero or negative; this differs from the subtract() method, which preserves those results. The symmetric-difference operator added in Python 3.15 is tracked separately because it has not been run on the available local interpreter.

Interactive Runnable example
Edit

Ready to run.

Quick check

What does left & right keep when both are Counters?

from collections import Counter
left = Counter(red=4, blue=1)
right = Counter(red=2, blue=3)
print(left & right)

Key takeaways

  • Counter is a dict subclass that tallies hashable items; a missing key lookup returns zero without adding that key.
  • most_common() ranks items by count, and ties retain first-seen order.
  • update() adds counts; subtract() preserves zero and negative counts, unlike Counter subtraction with the - operator.
  • elements() repeats items for positive integer counts, while total() sums counts.
  • Counter arithmetic is useful for multiset questions; deque and heapq remain the owners of end-based and priority-based queue behavior.
Was this page helpful?

Mark this learning resource complete to track your learning progress.