Python Collections — Counter, defaultdict, deque, and namedtuple
The built-in list, dict, and set cover most work, and the collections module covers four jobs they handle poorly. Counter counts things. A defaultdict creates the value for a missing key on its own, so grouping and counting code drops its key checks. A deque adds and removes at both ends, and can cap its own length. A namedtuple keeps tuple behavior and gives the fields names. This guide shows each type with a small working program and the exact output it prints.
Written November 12, 2026 · Tested with Python 3.12.3 · 11 min read
- The main program: Counter counts for you
- Counter arithmetic keeps only positive counts
- defaultdict builds the missing value for you
- Counting with defaultdict, and turning the factory off
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
The collections module ships container types that extend what the built-in types do. Each type in this guide solves one plain problem. Counting items by hand means a loop, a dict, and a check for whether the key exists yet. Grouping items means the same check before every append. A list removes from its left end slowly, because every other item has to move. A plain tuple refers to its parts by position, so a reader has to remember which position means what. The four types below remove those four frictions, and each one still behaves like the built-in it extends: a Counter is a dict, a defaultdict is a dict, a deque works in a for loop, and a namedtuple is a tuple.
The main program: Counter counts for you
A Counter takes an iterable and counts how many times each item appears. The result is a dict whose keys are the items and whose values are the counts:
from collections import Counter
counts = Counter(["red", "blue", "red", "green", "blue", "red"])
print(counts)
print(counts["red"])
print(counts["yellow"])
print(counts.most_common(2))
print(sorted(counts.elements()))
The exact output:
Counter({'red': 3, 'blue': 2, 'green': 1})
3
0
[('red', 3), ('blue', 2)]
['blue', 'blue', 'green', 'red', 'red', 'red']
Reading a key that was never counted returns zero instead of raising KeyError, which is why the third line prints 0 for yellow. That one behavior makes a Counter safe to query for items that may not have shown up at all. The most_common method returns the counts in falling order, as key and count pairs, and the argument caps how many pairs come back. The elements method hands the original items back, each one repeated as many times as its count, and sorting that output restores the input as a sorted list.
Counter arithmetic keeps only positive counts
Counters support arithmetic, and the operators follow one rule: a result keeps only counts above zero. Zero and negative counts fall out of an addition, a subtraction, an intersection, and a union. A leading plus sign on its own applies the same rule to a single Counter:
from collections import Counter
first = Counter(a=3, b=1, c=0, d=-1)
print(first)
print(+first)
second = Counter(a=1, b=2)
print(first + second)
print(first - second)
print(first & second)
print(first | second)
first.update(["a", "c"])
print(first)
The exact output:
Counter({'a': 3, 'b': 1, 'c': 0, 'd': -1})
Counter({'a': 3, 'b': 1})
Counter({'a': 4, 'b': 3})
Counter({'a': 2})
Counter({'a': 1, 'b': 1})
Counter({'a': 3, 'b': 2})
Counter({'a': 4, 'b': 1, 'c': 1, 'd': -1})
Addition adds the counts key by key, and subtraction takes them away, so the b count of 1 minus 2 drops out of the subtraction result instead of printing as a negative number. The intersection keeps the smaller count for each key, and the union keeps the larger one. The update method works differently: it adds counts in place, the way dict update does, and it does not clean up entries the operators would drop. The last line still carries the zero-count key raised to one by the update, and the negative entry that sat in the Counter all along. When a count must be allowed to reach zero and stay visible, plain dict-style assignment or update is the right tool, and the operators are the wrong one.
defaultdict builds the missing value for you
A defaultdict is a dict with one change: reading a missing key calls a factory function, stores the result under that key, and returns it. Passing list as the factory turns grouping into an append with no key check first:
from collections import defaultdict
groups = defaultdict(list)
pairs = [("fruit", "apple"), ("veg", "carrot"), ("fruit", "pear")]
for kind, name in pairs:
groups[kind].append(name)
print(dict(groups))
print(groups["drink"])
print("drink" in groups)
print(groups.default_factory)
The exact output:
{'fruit': ['apple', 'pear'], 'veg': ['carrot']}
[]
True
<class 'list'>
The first time the loop meets a kind, the factory makes an empty list for it, and the append lands in that list. The same call pattern groups any stream of key and value pairs: log lines by level, files by suffix, orders by state. The third block of output carries the catch. Reading the missing key drink did not just return an empty list; it stored one, so the key test right after returns True. A plain read through square brackets changes a defaultdict. Code that only wants to look, without adding the key, uses the get method instead. The factory itself sits on the default_factory attribute, which the last line prints.
Counting with defaultdict, and turning the factory off
Passing int as the factory gives each missing key a starting value of zero, which makes a counting loop as short as the grouping one:
from collections import defaultdict
counts = defaultdict(int)
for word in "one two one three two one".split():
counts[word] += 1
print(dict(counts))
print(counts["four"])
counts.default_factory = None
try:
print(counts["five"])
except KeyError as exc:
print("KeyError", exc)
The exact output:
{'one': 3, 'two': 2, 'three': 1}
0
KeyError 'five'
Each increment reads the key first, so a word seen for the first time starts at zero and lands at one. Reading four stores zero under that key, the same read-changes-the-dict behavior from the grouping section. Setting default_factory to None turns the factory off for good: from that point the dict raises KeyError for a missing key, like a plain dict. That is the standard way to freeze a finished defaultdict before handing it to code that should treat missing keys as errors instead of quietly creating them.
deque works at both ends
A deque, pronounced deck, is a sequence built for adding and removing at both ends. A list does the right-end work well and the left-end work slowly. A deque does both at full speed, with a matched pair of methods for each end:
from collections import deque
d = deque([2, 3])
d.append(4)
d.appendleft(1)
print(list(d))
print(d.pop())
print(d.popleft())
print(list(d))
d.rotate(1)
print(list(d))
d.rotate(-1)
print(list(d))
The exact output:
[1, 2, 3, 4]
4
1
[2, 3]
[3, 2]
[2, 3]
The append and appendleft methods add to the right and the left, and pop and popleft remove and return from the right and the left. That pair of pairs is the whole case for the type: queues, work lists, and sliding windows all add at one end and take from the other. The rotate method moves items from one end to the other in place. A positive count takes that many items from the right and puts them on the left, a negative count does the reverse, and rotating a two-item deque by one and then back by one returns it to its starting order, as the last two lines show. Printing a deque through list keeps the output readable; the deque itself prints with its own name around the same items.
A maxlen deque keeps only the newest items
A deque can carry a maximum length. Once it is full, adding an item at one end drops an item from the other end to make room:
from collections import deque
recent = deque(maxlen=3)
for value in range(5):
recent.append(value)
print(list(recent))
print(recent.maxlen)
recent.extendleft([9, 8])
print(list(recent))
The exact output:
[0]
[0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
3
[8, 9, 2]
Five values go in and only the last three stay, with no size check anywhere in the calling code. That makes a maxlen deque the short way to keep a rolling tail: the last few log lines, the most recent readings, the newest entries in a feed. The extendleft line shows the drop rule at the other end. It adds its items one at a time to the left, so 9 lands first and 8 lands in front of it, and each add pushes one item off the right: the 4 goes when 9 arrives, and the 3 goes when 8 arrives, leaving 2 as the only survivor of the original three.
namedtuple gives tuple fields names
The namedtuple factory builds a tuple subclass whose positions also answer to names. The result still unpacks, indexes, and compares like a tuple, and the fields read by name as well as by number:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"], defaults=[0, 0])
p = Point(3, 4)
print(p)
print(p.x, p[1])
print(p._fields)
print(Point())
q = p._replace(x=10)
print(q)
print(p)
print(q._asdict())
x, y = q
print(x, y)
The exact output:
Point(x=3, y=4)
3 4
('x', 'y')
Point(x=0, y=0)
Point(x=10, y=4)
Point(x=3, y=4)
{'x': 10, 'y': 4}
10 4
The defaults argument supplies values from the right, so Point() with no arguments fills both fields with zero, and Point(3) would set x and leave y at zero. Like every tuple, a namedtuple cannot change in place. The _replace method answers that need the tuple way: it returns a new value with the named fields swapped, and the original prints unchanged right after. The _asdict method converts the value to a plain dict keyed by field name, which is the form most other code, and most file formats, want. Reach for a namedtuple when a value is a fixed small record passed around as data. When the value needs methods of its own, a dataclass or a plain class is the better fit.
Which type for which job
| Job | Type | Why |
|---|---|---|
| Count how often each item appears | Counter | One call counts the whole iterable, and a missing item reads as zero |
| Combine two tallies | Counter with +, -, &, or | | The operators keep the smaller or larger count per key and drop counts at zero or below |
| Group items under keys | defaultdict with list | The factory makes the empty list, so the loop is an append with no key check |
| Count with a plain dict shape | defaultdict with int | Missing keys start at zero; setting the factory to None restores KeyError |
| Add and take at both ends | deque | append, appendleft, pop, and popleft all run at full speed |
| Keep only the newest few items | deque with maxlen | A full deque drops the far end on its own when a new item arrives |
| Give a small record named fields | namedtuple | Fields read by name and by position, and the value stays a tuple |
| Fixed record that needs its own methods | A class or dataclass instead | namedtuple carries data only; behavior belongs on a class |
Checklist
- Before querying a Counter for an item that may be absent, remember the answer is zero, not an error; code that must reject unknown items needs its own key test.
- Before using a Counter operator, check whether zero or negative counts must survive; the operators drop them, and update keeps them.
- Before reading a defaultdict with square brackets in lookup-only code, switch to get; a bracket read stores the factory value under the missing key.
- Before handing a finished defaultdict to strict code, set its default_factory to None so missing keys raise KeyError again.
- Before keeping a rolling tail in a list with manual trimming, set a maxlen on a deque and let the drop rule do the trimming.
- Before naming tuple positions in comments across a codebase, make the tuple a namedtuple and let the field names carry that information.
Related guides on this site
- Python Lists, Dicts, and Sets — the built-in containers this guide extends; each type here starts where one of those leaves off.
- Python Loops and Conditionals — for, while, if, range, and enumerate — the grouping and counting patterns in this guide are for loops over pairs and words.
- Python Classes and Objects — init, Methods, Inheritance, and Dataclasses — the dataclass in that guide is the step up from a namedtuple when a record needs methods.
- Python Modules and Packages — import, Aliases, and name — collections is a standard library module, imported the way that guide describes.
Sources
- Python Standard Library, collections — the Counter, defaultdict, deque, and namedtuple documentation this guide follows, including the arithmetic and maxlen rules.
- Python Tutorial, Data Structures — the list, dict, and tuple behavior these types extend.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.