Lesson 7 of 52Collections
Tuples and Sets
Use tuples for fixed records and unpacking, sets for fast membership, and know what hashing costs and which immutable type fits.
Lists are not the only collection, and picking the right one is a sign of experience. A tuple says "these values belong together and will not change". A set says "I only care whether something is in here", and answers that question almost instantly, even with millions of items. Swapping a list for a set is one of the most common fixes for slow code, in real projects and in interviews.
Tuples: fixed groups of values
A tuple is an ordered collection like a list, but immutable: once made, you cannot add, remove or replace items. You write it with commas, usually inside parentheses.
Press Run (⌘ Enter) to see what happens.It is really the comma that makes a tuple, not the parentheses. That is why a one-item tuple needs a trailing comma.
Why use something that can do less than a list? Because "cannot change" is a promise. A function that returns (latitude, longitude) tells the caller this is one fixed record. Tuples are also slightly smaller and faster than lists, and, as you will see shortly, they can be used as dict keys and set members while lists cannot.
Packing and unpacking
Writing a, b packs values into a tuple. Putting several names on the left of = unpacks a sequence into them. This is used everywhere in Python.
Press Run (⌘ Enter) to see what happens.The *rest form collects "everything else" into a list. It can go anywhere: *init, last = items grabs the last item and everything before it. If the number of names does not match the number of values (and there is no star), you get a ValueError.
What does this print?
head, *middle, tail = [1, 2, 3, 4, 5] print(head, middle, tail)
Immutable, but not frozen all the way down
A tuple's items cannot be replaced, but if an item is itself mutable, like a list, that list can still change. The tuple holds a reference to the list, and that reference does not change.
The tuple holds the int 1 and a reference to a list.
NamedTuple: a tuple with field names
Plain tuples get hard to read once they hold more than two or three values. What is row[3]? A reviewer has to go and find out. A named tuple keeps everything a tuple does (immutable, unpackable, hashable, cheap) and adds names for each position.
Press Run (⌘ Enter) to see what happens.typing.NamedTuple is the modern spelling, with type hints and defaults. The older collections.namedtuple("Point", "x y") builds the same kind of class and still shows up in older code. Some standard library results, like os.stat() and urllib.parse.urlparse(), behave the same way: fields by name or by position.
The last line is the catch. A named tuple is a tuple, so it compares equal to any plain tuple with the same values, and two different named tuple types with the same values compare equal to each other too. It also still supports len(), indexing and iteration, which means callers can start depending on field positions, so adding a field in the middle later breaks them. That is fine for small, stable records like coordinates, rows from csv or sqlite3, or a function that returns (status, body) with names. When the record has behaviour, needs validation, or will grow over time, reach for a dataclass instead (see the Dataclasses lesson), which compares only with its own type and has no positions to lean on.
What does this print?
from typing import NamedTuple class Money(NamedTuple): amount: int currency: str class Item(NamedTuple): sku: int name: str print(Money(5, "GBP") == (5, "GBP"), Money(5, "GBP") == Item(5, "GBP"))
Sets: unique items, fast lookups
A set is an unordered collection of unique items. Write it with curly braces, or call set() on any iterable. Duplicates simply disappear.
Press Run (⌘ Enter) to see what happens.Sets are unordered, so there is no s[0], and the printing order is not something to rely on. When you need a stable order, wrap the set in sorted(...).
The real superpower is membership. Checking x in some_list looks at items one by one: O(n). Checking x in some_set jumps straight to where x would be stored, using a hash (a number computed from the value): O(1) on average. With a million items, that is the difference between up to a million comparisons and about one.
Press Run (⌘ Enter) to see what happens.Set algebra
Sets support the operations from maths class, with operators that read nicely:
Press Run (⌘ Enter) to see what happens.Match each question to the set operation that answers it.
What does this print?
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a - b), len(a | b))Hashable things only, and frozenset
Sets (and dict keys) can only hold hashable values: values whose hash never changes. In practice, immutable built-ins (int, float, str, bool, None, and tuples of those) are hashable. Mutable ones (list, dict, set) are not, because if they changed after being stored, Python would look in the wrong place for them.
Press Run (⌘ Enter) to see what happens.A frozenset is an immutable set. Because it cannot change, it is hashable, so you can put sets inside sets or use them as dict keys: frozenset({"read", "write"}).
Under the hood: hashing, collisions and cost
"Sets are O(1)" is true on average, and knowing why tells you when it stops being true. A set is a hash table: an array of slots. To add or find x, Python computes hash(x), uses the low bits of that number to pick a slot, and looks there. If the slot is empty, x is not in the set. If it holds something with the same hash, Python calls == to make sure it is really the same value. Two values landing in the same slot is a collision; CPython then probes other slots in a fixed pattern until it finds x or an empty slot.
For small ints, hash(n) is n itself. The table has 8 slots, so 3 goes to slot 3 % 8 = 3, and 12 to slot 4.
That picture explains the three things that make sets slow in practice:
- Hashing is not free. A lookup costs one
hash()call plus usually one==. For ints that is trivial. For strings, CPython computes the hash once and caches it on the string object, so repeated lookups with the same string are cheap. For your own classes,__hash__and__eq__are Python methods that run on every lookup. - Bad hashes destroy performance. If many values share a hash, every lookup walks a long probe chain and compares against each one, and O(1) degrades towards O(n). The run below shows it with a deliberately terrible
__hash__. - Sets cost memory. To keep collisions rare, the table is always partly empty. A set of ten thousand ints takes several times the memory of a list of the same ints.
Press Run (⌘ Enter) to see what happens.With a good hash, building the set takes 1,000 hashes and essentially no equality checks (Python only calls == when two full hash values match), and a lookup takes one of each. With a constant hash, building the same set takes hundreds of thousands of == calls: it has become quadratic. Real code rarely returns a constant, but hashing only one field that has few distinct values (a status, a country code) has the same effect.
The hash and equality contract
The rule that keeps all this working: if a == b, then hash(a) == hash(b) must hold, and an object's hash must not change while it sits in a set or dict. Python helps you here. If a class defines __eq__ but not __hash__, Python sets __hash__ to None, so its instances are unhashable instead of silently broken. Dataclasses follow the same rule: a plain @dataclass is unhashable, and @dataclass(frozen=True) gets a hash built from its fields. If you write __hash__ yourself, hash the same fields __eq__ compares, usually as a tuple: return hash((self.sku, self.currency)).
One more surprise: the iteration order of a set of strings changes from one run of Python to the next. String hashes are randomised per process (unless PYTHONHASHSEED is set) so attackers cannot craft inputs that all collide and slow a server down. Never write a test that depends on the order a set prints in.
__eq__ to a class that compares self.email, but you do not write __hash__. What happens when you put an instance in a set?When a set is the wrong tool
Converting to a set is not always a win. Building a set is O(n) work plus extra memory, so it pays off only when you do many lookups. Turning a list into a set to check one item is slower than just scanning the list once.
Sets also throw away order and duplicates, which is sometimes exactly the information you needed. To de-duplicate while keeping the first-seen order, use a dict, whose keys are unique and keep insertion order:
Press Run (⌘ Enter) to see what happens.sys.getsizeof counts only the container, not the ints inside, but the gap is real: the set's table is bigger and partly empty by design. For a handful of items (say, under ten) a tuple membership check like if method in ("GET", "HEAD"): is perfectly fine and reads well.
What does this print?
steps = ["build", "test", "build", "lint", "test"] print(list(dict.fromkeys(steps)), len(set(steps)))
frozendict and the immutability family
Python now has an immutable partner for every core container. Python 3.15 (October 2026) added the last missing piece, a built-in frozendict (PEP 814):
DEFAULTS = frozendict(region="eu-west-2", retries=3)
DEFAULTS["retries"] # 3
DEFAULTS["retries"] = 5 # TypeError: it cannot be changed
cache = {DEFAULTS: "ok"} # hashable when its values are hashable
isinstance(DEFAULTS, dict) # False: it is not a dict subclassIt keeps insertion order and is hashable when its contents are. It is deliberately not a subclass of dict, so code that checks isinstance(x, dict) will reject it. Check against collections.abc.Mapping instead, which is better practice anyway. The browser on this site runs 3.14, so the block above is not runnable here; What Changed in Python 3.11 to 3.15 covers the rest of the release.
Before 3.15, the usual way to hand out a dict nobody can change was types.MappingProxyType. It is a read-only view, not a frozen copy: the code that owns the underlying dict can still change it, and everyone holding the proxy sees the change.
Press Run (⌘ Enter) to see what happens.| Mutable | Immutable partner | Hashable? |
|---|---|---|
list | tuple (or a NamedTuple) | If every item is |
set | frozenset | Yes (its items are always hashable) |
dict | frozendict (3.15+); MappingProxyType is only a view | frozendict if its values are |
bytearray | bytes | Yes |
a regular @dataclass | @dataclass(frozen=True) | If its fields are |
Remember the tuple-holding-a-list picture from earlier: all of these are shallow. A frozendict whose value is a list is immutable at the top and mutable underneath, and it becomes unhashable because the list is. Immutability is worth having for configuration, constants, cache keys and anything shared between threads, because a value nobody can change cannot be changed by the wrong code at the wrong time.
Which one should you use?
| You need | Use |
|---|---|
| An ordered collection you will change | list |
| A fixed record, a return of several values, or a dict key | tuple |
| A small, stable record with field names | NamedTuple (a dataclass if it will grow) |
| Uniqueness, or fast "is this in here?" checks | set |
| A set that must be hashable | frozenset |
| De-duplicate but keep the original order | dict.fromkeys(items) |
| A dict nobody can change | frozendict (3.15+), or MappingProxyType as a read-only view |
Smallest and largest
Write min_max(nums) that returns a tuple (smallest, largest).
min_max([3, 1, 4]) → (1, 4)
min_max([7]) → (7, 7)nums has at least one number. (Tests show tuples as lists, so (1, 4) appears as [1, 4].)
In both lists
Write common_items(a, b) that returns the items that appear in both lists, with no duplicates, sorted.
common_items([1, 2, 3, 4], [3, 4, 5]) → [3, 4]
common_items([1, 1, 2], [1, 1]) → [1]- tuple
- An ordered, immutable sequence. The comma makes it:
(5,)is a one-item tuple. - unpacking
- Assigning a sequence to several names at once:
a, b = b, a, orfirst, *rest = items. - set
- An unordered collection of unique, hashable items with O(1) average membership checks.
- hashable
- Has a hash that never changes. Immutable values like ints, strs and tuples of them are hashable; lists are not.
- frozenset
- An immutable, hashable set. Can be a dict key or a member of another set.
- set algebra
|union,&intersection,-difference,^symmetric difference.- NamedTuple
- A tuple subclass with named fields. Still compares equal to plain tuples with the same values.
- hash collision
- Two values whose hashes point to the same slot. Many collisions turn O(1) lookups into O(n).
- frozendict
- A built-in immutable mapping added in Python 3.15. Hashable when its values are; not a
dictsubclass. - MappingProxyType
- A read-only view of a dict. The owner can still change the dict underneath.