runtime
76 / 250
lesson 76 Collections & Itertools · intermediate

Count and rank with Counter

Counting how often each value appears is one of the most common jobs in data work. `Counter`, from the standard library's `collections` module, does the counting, gives 0 for values it never saw, and ranks the results.

You'll be able to
  • Bring a tool in from the standard library with from collections import Counter
  • Count a list in one step, read a count (0 for an unseen value), and add more counts with += or update
  • Rank with most_common(n), and know how it orders ties
The idea

In the Collection Algorithms module you counted with a dictionary: start each new key at 0, then add 1. It works, but almost every program that reads data needs it, so Python ships a ready-made counter.

Python comes with a standard library: modules of extra tools that are installed with Python but not loaded until you ask. from collections import Counter loads the collections module and makes its name Counter available in your program. Put imports at the top of the file.

Counter(values) counts every value in a list. Reading a count works like a dictionary lookup, except that a value it never saw gives 0 instead of a KeyError. most_common(n) returns the top n as (value, count) pairs, highest first.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Repository events by type
from collections import Counter

event_types = ["PushEvent", "WatchEvent", "PushEvent", "IssuesEvent", "PushEvent", "WatchEvent"]
counts = Counter(event_types)
print(counts)
print(counts["PushEvent"], counts["ReleaseEvent"])
print(counts.most_common(2))

The import is not optional. Without it, Python has never heard of Counter:

example-2.py · Using Counter without importing it
counts = Counter(["PushEvent", "WatchEvent"])
print(counts)

A Counter is a dictionary underneath, so you can also add any amount to a count. Because a missing count starts at 0, units[product] += quantity needs no if first. To add 1 for every item of another list, counts.update(more_values) does it in one call.

example-3.py · Best sellers by units, not by order lines
from collections import Counter

def best_sellers(lines, n):
    units = Counter()
    for line in lines:
        units[line["product"]] += line["quantity"]
    return units.most_common(n)

lines = [
    {"product": "Travel Yoga Mat", "quantity": 2},
    {"product": "Deluxe Vase", "quantity": 1},
    {"product": "Travel Yoga Mat", "quantity": 3},
    {"product": "Nordic Candle", "quantity": 4},
]
print(best_sellers(lines, 2))

When to use it: whenever the question is *how many of each?* or *which are the most common?*: events per type, tags per question, units per product. Mistakes to avoid: Counter("python pandas") counts letters, because a text is a sequence of characters; split it into words first. most_common breaks ties by the order values were first seen, not alphabetically. And a Counter prints as Counter({…}); when a function's caller expects a plain dictionary or list, convert it (dict(counts), or the list from most_common).

Review
  • from collections import Counter loads a standard-library tool; the import goes at the top.
  • Counter(values) counts a list; a missing value counts as 0; += and update add more.
  • most_common(n) ranks the counts; ties keep first-seen order. Hand callers a plain dict or list.
  • Next: defaultdict, which builds the starting value for any new key, so grouping needs no setup line.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Count and rank with Counter — Collections & Itertools · Runtime