Tuples & sets
Immutable tuples, unpacking and NamedTuple; sets for uniqueness, fast membership and set algebra.
Lists are the default collection, but Python offers two other built-ins that often fit a problem better. Tuples are ordered and immutable — perfect for fixed records like coordinates or database rows. Sets are unordered collections of unique items with lightning-fast membership tests and mathematical operations.
Tuples: fixed, ordered records#
Tuples support indexing, slicing, in, len, count and index — everything lists do except changing contents:
Why use an immutable sequence?
- Safety — a tuple passed to a function can't be changed behind your back.
- Meaning — a tuple says "this is one record with a fixed structure"; a list says "a collection of similar things that may grow".
- Hashability — tuples of immutable values can be dictionary keys and set members; lists can't.
Tuple unpacking#
Unpacking is where tuples really shine. You've already used it for swapping and multiple return values:
Unpacking also works in loops, which is why iterating over dict.items() or enumerate() feels so natural:
Use _ for values you don't need: _, surname, _ = person.
Named tuples: records with field names#
point[0] doesn't say much. collections.namedtuple (or its typed cousin typing.NamedTuple) gives tuple fields names while keeping them immutable and lightweight:
For richer records with defaults and methods you'll later use dataclasses.
Sets: unique, unordered items#
A set stores each value at most once. Create one with braces or set():
Sets are unordered: you can't index them (tags[0] is an error), and printing may show items in any order. If you need a stable order, sort them: sorted(tags).
Adding and removing
Fast membership tests
Checking x in some_list scans items one by one. A set uses hashing, so x in some_set takes about the same time whether the set holds ten items or ten million. Whenever you check membership repeatedly, convert to a set first:
Set algebra
Sets support the operations you know from maths, as operators or methods:
Removing duplicates while keeping order
list(set(items)) removes duplicates but scrambles the order. To keep the first occurrence of each item in order, use dict.fromkeys (dicts preserve insertion order):
Frozen sets
A frozenset is an immutable set, so it can be a dict key or live inside another set: frozenset({"read", "write"}).
Hashability in one paragraph#
Sets and dict keys rely on a value's hash — a number computed from its contents. If the contents could change, the hash would change and Python would lose track of the item. That's why only hashable (effectively immutable) values are allowed: numbers, strings, tuples of hashables, frozensets. Lists, dicts and sets are not:
Choosing the right collection#
Common mistakes#
(5)is not a tuple — write(5,).{}is an empty dict, not an empty set — useset().- Relying on set order — sort when you need an order.
- Trying to index a set — convert to a list or sorted list first.
What's next#
The last and arguably most important built-in collection is the dictionary: fast lookups by key, and the backbone of JSON, configuration and countless programs.
Check your understanding
Quick quiz
1.How do you create a tuple containing just the number 5?
2.What does
{1, 2, 3} & {2, 3, 4}return?3.Why can't you put a list inside a set?
Finished reading?
Mark this lesson complete to track your progress.