Back to Explore
GuideVibeFix editorialUpdated Nov 26, 2026

Python collections from Zero: Counter, defaultdict, deque, and namedtuple, Measured Live

Measured live: in 30 visit records home appears 11 times, search 7, cart 5; three users did 4 actions each; the last-5 response-time averages are 128.0, 134.0 and 134.4 ms; a missing Counter key reports 0 without creating it, defaultdict really creates the key; deque has no slicing.

Real photograph of hands typing on a laptop showing Python code on screen, with a plant, glasses and a mug on the desk (illustrative photo)

Introduction: dict and list work, but the code gets wordy

At some point every Python programmer runs into the same three jobs: counting how many times something appears, grouping a pile of things by some key, and keeping only the most recent few records while the old ones drop away. You can do all three with dict and list. The problem is that the code gets wordy and easy to get wrong: counting means checking whether the key exists first, grouping means checking whether the list was created first, and a sliding window means computing indexes and cutting off old data yourself. Python's standard library has a module called collections that packages these three jobs into ready-made containers: Counter does the counting, defaultdict does the grouping, deque handles fast access at both ends and sliding windows, and namedtuple gives names to the positions inside a tuple.

None of the four needs a third-party package; import collections is enough. This guide does not recite definitions. It works from a real run on a real machine: three fixed input datasets — 30 page visits, 12 user events, 10 response times — run through the four tools one by one, and every number quoted comes from the demo script demo257_g1.py, whose full transcript is attached at the end. By the end you should be able to swap your hand-written loops for these containers directly: Counter for counting, defaultdict for grouping, deque for the most recent N items, namedtuple when a tuple gets hard to read.

1. Environment and data: fix the numbers first

First, the environment. The demo ran on one machine, Python 3.12.3, script demo257_g1.py, once in Chinese and once in English, both exiting 0, with identical numbers in both transcripts. The input data is hard-coded in the script, not fetched live, so every number below is reproducible rather than a one-off.

The three datasets look like this. The first is 30 page visits in visit order: home appears 11 times, search 7 times, cart 5 times, product 4 times, checkout 3 times — 30 records in total, 5 distinct pages. The second is 12 user events, each a (user, action) pair: three people — amy, ben, cid — 4 actions each, each doing login, view, buy and logout exactly once, in different orders. The third is 10 response times in milliseconds, oldest first: 120, 98, 140, 210, 95, 130, 88, 175, 105, 142. The data is deliberately tiny, small enough to check by hand, so you can see at a glance whether the tools got it right.

2. Counter: counting, in one line

Start with the most common job: counting how many times each page was visited. The hand-written loop looks like this: build an empty dict, loop over the records, set the key to 0 if it is missing, then add 1 — four lines. With Counter it is one line: counts = Counter(VISITS). The measured result is {'home': 11, 'search': 7, 'cart': 5, 'checkout': 3, 'product': 4}, exactly the same as the hand-written loop — the script compares the two at the end and the result is True.

from collections import Counter

VISITS = ["home", "search", "home", "cart", ...]  # 30 records
counts = Counter(VISITS)
counts.total()        # 30: total visits
len(counts)           # 5: distinct pages
counts.most_common(3) # [('home', 11), ('search', 7), ('cart', 5)]

Counter is a dict subclass, so almost everything a dict can do, it can do — plus three counting tricks of its own. The first is most_common(n), which reports the top n directly. Measured: most_common(3) is [('home', 11), ('search', 7), ('cart', 5)] — home 11 times, search 7, cart 5. With no argument, most_common() lists all 5 in descending order, the last being ('checkout', 3), the least common page. For leaderboards, finding the most popular or the least popular, one method call is enough — no sorted with a lambda.

The second trick is total(), which reports the sum. Measured: counts.total() is 30, matching the 30 records. total() was added in Python 3.10, so it works fine on 3.12; on a much older interpreter, sum(counts.values()) means the same thing.

The third trick is the easiest to miss: looking up a missing key does not raise KeyError, it returns 0. Measured: counts['about'] is 0, because the about page never appears. And one step further: after that lookup, is 'about' in the counter? Measured: False — Counter only reports 0, it does not actually create the key. That detail matters, and the next-but-one section will contrast it with defaultdict: one reports a number without creating a key, the other really creates the key. Two very different behaviours.

A common beginner question: what can Counter count? Anything hashable: strings, numbers, tuples. Lists and dicts do not work, because they are not hashable. Counting words, pages, status codes, user IDs — all Counter jobs. If you want to count lists, convert them to tuples first.

3. Counter arithmetic: today minus yesterday

Counter does more than count; it does arithmetic. Suppose yesterday's data was home 8, search 6, cart 3, product 2, checkout 1 — 20 visits in total. Today's data is the 30 visits from the previous section. Subtract the two Counters, counts - yesterday, and the measured result is {'home': 3, 'search': 1, 'cart': 2, 'checkout': 2, 'product': 2}. In words: home is up 3, search up 1, cart up 2, checkout up 2, product up 2.

yesterday = Counter({"home": 8, "search": 6, "cart": 3,
                     "product": 2, "checkout": 1})
diff = counts - yesterday
# {'home': 3, 'search': 1, 'cart': 2, 'checkout': 2, 'product': 2}

Two details are worth remembering. First, Counter subtraction keeps only positive results: if a page went down today, it simply does not appear instead of showing a negative number. To see the full picture including negatives, use the subtract() method, which keeps negative counts. Second, Counter addition adds counts rather than merging sets: Counter({'a': 2}) + Counter({'a': 3}) is {'a': 5}. Both operations are handy for daily and weekly reports: today minus yesterday is growth; two periods added together is the total.

One more note on most_common's ordering: elements with equal counts are ordered by first encounter. The demo data has no ties, so you cannot see it there, but the official docs spell it out: Counter('abracadabra').most_common(3) is [('a', 5), ('b', 2), ('r', 2)] — b and r both have 2, and b comes first because it appears first. Knowing this rule means tied rankings will not look random to you.

4. defaultdict(list): grouping, without checking the key first

The second job is grouping: 12 user events, filed under each user. The hand-written dict version goes: loop over the events, check whether the user is in the dict, create an empty list if not, then append. defaultdict removes the check: defaultdict(list) means that when a missing key is encountered, an empty list is built automatically with list().

from collections import defaultdict

by_user = defaultdict(list)
for user, action in EVENTS:
    by_user[user].append(action)
# {'amy': ['login', 'view', 'buy', 'logout'],
#  'ben': ['login', 'view', 'buy', 'logout'],
#  'cid': ['login', 'view', 'buy', 'logout']}

The measured result: amy did 4 actions ['login', 'view', 'buy', 'logout'], ben 4, cid 4 — all three identical, because the input was designed that way, each person doing login, view, buy and logout exactly once. After grouping, looking up one person is just by_user['amy'].

Now the key contrast: what happens when you look up a user who does not exist? Measured: by_user['dan'] returns [], an empty list. And after that lookup, is 'dan' in the dict? Measured: True — defaultdict really did create the dan key, with that empty list as its value. This is the exact opposite of the previous section: Counter reports 0 for a missing key without creating it; defaultdict really creates the key.

That difference is defaultdict's biggest trap and its biggest benefit. The benefit is that grouping code never needs an if check again. The trap is that a casual lookup stuffs keys into your dict. If you only want to check whether someone is there, never use by_user['dan'] directly — use 'dan' in by_user or by_user.get('dan'), because get does not create the key. A subtler version of the same trap: when you loop over a defaultdict to print it, it may contain a pile of empty lists created by casual lookups, and your data is dirty. Remember one sentence: square brackets on a defaultdict mean "build one if it is missing", not just "look it up".

The argument to defaultdict is a "factory function": a function that takes no arguments and returns a fresh value each time it is called. list is a factory, int is a factory, set is a factory. Pass list and you get an empty list, pass int and you get 0, pass set and you get an empty set. The factory returns a brand-new value on every call, so each key gets its own independent list — they never leak into each other. Never pass a ready-made list, such as defaultdict([]): that is not a factory, and Python raises an error, because the first argument must be callable.

5. defaultdict(int): the same counting job, in another shape

defaultdict can count as well as group. Count the 12 events by action: per_action = defaultdict(int), loop over the events, per_action[action] += 1. The measured result is {'login': 3, 'view': 3, 'buy': 3, 'logout': 3}, totalling 12. Three users each doing login, view, buy and logout once means each action appears 3 times — the books balance.

per_action = defaultdict(int)
for _, action in EVENTS:
    per_action[action] += 1
# {'login': 3, 'view': 3, 'buy': 3, 'logout': 3}, total 12

This does the same thing as Counter, so when do you use which? The rule of thumb: for plain counting, use Counter — one line, plus most_common and total ready to go. When counting is just one step inside grouping logic, or the values are more than counts, use defaultdict(int). The most common mixed case is grouping first and counting second: group by user with defaultdict(list), then count each person's actions with len() — more readable than Counter there.

One older idiom is worth comparing: dict.setdefault(key, []).append(value). setdefault also does "create it if the key is missing", with the same effect as defaultdict(list), but you have to write setdefault on every line, which reads awkwardly. defaultdict folds that pattern into the container itself, leaving only the append in the loop body. If your code is full of setdefault, that is when defaultdict should step in.

6. deque(maxlen=5): keep the last 5, drop the old ones automatically

The third job is a sliding window: response times where only the most recent 5 matter, new values coming in and old ones dropping out on their own. A list can do it: append one, check whether the length overflowed, delete element 0. But deleting element 0 from a list shifts every element after it one place forward, which gets slow as data grows — and you have to do the length check yourself every time. deque is built for access at both ends: append adds to the right, appendleft to the left, pop takes from the right, popleft from the left, both ends fast.

Even easier is the maxlen argument. deque(TIMES[-5:], maxlen=5) means: keep only the last 5, the length cap is 5, and anything beyond it is automatically dropped from the other end. Measured: the 10 times are 120, 98, 140, 210, 95, 130, 88, 175, 105, 142, and the last 5 are [130, 88, 175, 105, 142], with an average of 128.0 ms. After append(160), the window becomes [88, 175, 105, 142, 160] — 130 dropped out — and the average becomes 134.0 ms. After another append(90), the window becomes [175, 105, 142, 160, 90] — 88 dropped out — and the average becomes 134.4 ms. Each new value pushes the oldest one out, the length stays 5, and you never compute an index or delete anything yourself.

from collections import deque

window = deque([130, 88, 175, 105, 142], maxlen=5)
window.append(160)  # [88, 175, 105, 142, 160], average 134.0 ms
window.append(90)   # [175, 105, 142, 160, 90], average 134.4 ms

The averages work out like this: (130 + 88 + 175 + 105 + 142) / 5 = 640 / 5 = 128.0; (88 + 175 + 105 + 142 + 160) / 5 = 670 / 5 = 134.0; (175 + 105 + 142 + 160 + 90) / 5 = 672 / 5 = 134.4. The three averages are 128.0, 134.0 and 134.4 ms, computed by the script, not by hand.

rotate is another handy deque method: rotate(1) moves the last element on the right to the far left, turning the whole queue one step right. Measured: [175, 105, 142, 160, 90] after rotate(1) becomes [90, 175, 105, 142, 160] — 90 moved from the tail to the head; then rotate(-1) turns it back to [175, 105, 142, 160, 90]. For round-robin, ring buffers, and shuffling order back and forth, rotate reads far better than hand-written slicing.

But deque has two limits, both verified in the demo. First, deque cannot be sliced: window[1:3] raises TypeError, with the message "sequence index must be integer, not 'slice'". To slice a chunk, convert to a list first. Second, indexing a single element works fine — measured window[0] is 175 — but inserting or deleting in the middle is slow; the middle is not its strength. Remember its place: fast at both ends, and do not ask it for slicing or middle operations.

The official tutorial states the selection rule directly: using a list as a queue is slow when removing from the front, because all the other elements have to shift by one; to implement a queue, use collections.deque, which was designed to have fast appends and pops from both ends. Log tails, the most recent N records, sliding windows — that is deque's home ground. For frequent indexing, slicing and sorting, stick with list.

7. namedtuple: giving names to a tuple's positions

The fourth tool fixes a different pain: tuples read by index are unreadable. v = ('amy', 'checkout', 42) — who is v[0]? Which page is v[1]? What number is v[2]? Two months later even the author has to look up the definition. namedtuple names each position:

from collections import namedtuple

Visit = namedtuple("Visit", ["user", "page", "seconds"])
v = Visit("amy", "checkout", 42)
v.user     # 'amy'
v.page     # 'checkout'
v.seconds  # 42

Measured: Visit('amy', 'checkout', 42) prints as Visit(user='amy', page='checkout', seconds=42), each field named, readable at a glance. v.user is amy, v.page is checkout, v.seconds is 42. Converting to a dict works too: v._asdict() is {'user': 'amy', 'page': 'checkout', 'seconds': 42}. And underneath it is still a tuple: unpacking by index still works, v[0], v[1], v[2] being amy, checkout, 42, so old code does not break.

namedtuple is immutable, like a tuple: once built, you cannot change a field. To change one, build a new record, or use v._replace(seconds=43) to produce a modified copy. For records with few fields, a fixed shape, and mostly read-only use — log lines, coordinates, config entries — namedtuple beats dict: no quotes around keys, no risk of mistyping a key name; and it beats writing a class: no __init__ to write. But if the record changes fields often, has many fields, or needs methods, write a class or use a dataclass instead of forcing namedtuple.

8. The control group: the four-line plain-dict version

To see clearly what the four tools actually save, the script ends with a control group: the same 30 visit records counted with a plain-dict loop. Four lines: loop over the records, set the key to 0 if missing, add 1. The result is {'cart': 5, 'checkout': 3, 'home': 11, 'product': 4, 'search': 7}, exactly the same as Counter's result — the comparison is True. The tools do not add new capabilities; they absorb the boilerplate — the "check whether the key exists" and index arithmetic — into the container.

That is what the collections module is for: not things dict and list cannot do, but things they make wordy, packaged as ready-made containers. Counting, grouping, sliding windows, named tuples — these four patterns show up constantly in real code, and every hand-written version repeats the same checks and index math. With the ready-made containers, the code is half as long and half as likely to be wrong.

Bar chart: how often each page appears in the 30 visit records — home 11, search 7, cart 5, product 4, checkout 3

9. Which one? A comparison table

With all four on the table, picking one is a one-liner. To count how often things appear, use Counter. To file things into groups by a key, use defaultdict(list). To count within groups, use defaultdict(int) or Counter. To keep only the most recent N items, with new ones pushing old ones out, use deque(maxlen=N). When a tuple has too many positions to read, use namedtuple to name them.

Three more tripwires. First, Counter returns 0 for a missing key without creating it; defaultdict really creates the key when you look one up. If you only want to check presence, use in or .get() — do not touch a defaultdict with square brackets. Second, deque cannot be sliced, and middle inserts and deletes are slow; both ends are its home. Third, namedtuple cannot be changed after creation; use _replace() to produce a new copy, or switch to a dataclass.

One more rule about whether it is worth it: for a tiny one-off count, a hand-written dict loop is fine — there is no need to reach for a tool just to use one. collections pays off on patterns that repeat: the same counting logic appearing for the third time in your code should become a Counter; the same grouping check appearing for the third time should become a defaultdict.

Here is how the four combine in a real scenario, so you can see them working together. Suppose you have a website access log, each line a status code plus a date. You want three answers: which status code is most common, which day had the most errors, and whether the average response time over the last hour is getting worse. The first is a Counter job: throw all the status codes into a Counter and most_common(3) gives the top three. The second is a defaultdict(list) job: group by date, one list per day, then count the 500s in each group. The third is a deque(maxlen=60) job: one response time per minute, keep the last 60, and the average tells you the trend. Three questions, three containers, one line each, and together they form a small log tool with no key checks and no index arithmetic. Most data statistics in vibe-coded projects have this shape: count first, group second, watch the recent window last — and when the tools are right, the code reads like the problem itself read aloud.

10. Cheat sheet and checklist

The whole guide in one cheat sheet. Counter(iterable): count things. most_common(n): the top n. total(): the total. counts['missing key']: 0, no key created. Counter subtraction: only positive growth remains. defaultdict(list): group things, missing keys get an empty list automatically. defaultdict(int): count things, missing keys start at 0. defaultdict lookup of a missing key: really creates the key, be careful. deque(maxlen=N): sliding window, drops the oldest automatically when over length. deque.append / popleft: fast at both ends. deque.rotate(n): turn the whole queue n steps. deque cannot be sliced. namedtuple("Name", ["field", ...]): name a tuple's positions. ._asdict(): convert to dict. ._replace(): change a field and get a new copy.

Work through this checklist when you start. First, confirm what you are doing — counting, grouping, a sliding window, or naming a tuple — and pick the matching tool. Second, write one line of Counter or defaultdict, run it on small data, print it, and check the numbers against a hand count. Third, check the boundary: what happens on a missing key — does it report 0 or create a key, and is that what you want? Fourth, remember to set maxlen on a deque, or the window will grow forever; and remember not to name a namedtuple field the same as a method, such as _asdict. Fifth, run demo257_g1.py and compare with the transcript: top three home 11, search 7, cart 5; three people with 4 actions each; window averages 128.0, 134.0, 134.4 ms. Once the numbers match, move it into your own code.

11. What this guide did not verify

An honest boundary. First, the collections module also has ChainMap and OrderedDict, which this guide does not demo: ChainMap stacks several dicts into one view, and OrderedDict remembers insertion order — but plain dict has remembered order since 3.7, so OrderedDict is rarely needed now. Both follow the official docs. Second, this guide ran no benchmarks for performance: the tutorial's statement that deque is fast at both ends is qualitative, and exactly how much faster depends on data size — no measured number is claimed. Third, thread safety of Counter and defaultdict, and memory use on huge data, are not covered here; sharing a counter across threads needs proper concurrency handling. Fourth, the demo data is fixed at 30, 12 and 10 records; with real log volumes, most_common and grouping answers must be recomputed on real data — the method stays the same, the numbers change.

Still, the core of these four tools never changes: counting goes to Counter, grouping goes to defaultdict, the most recent N go to deque, and unreadable tuples go to namedtuple. Hand the key checks and index arithmetic to the standard library, and the code gets half as long and half as likely to be wrong. The rest is finding one place in your own code that is hand-writing a count or a grouping, swapping in Counter or defaultdict, and seeing whether it really is easier.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles