Python Foundations·Lesson 7 of 67·beginner
Sets and tuples
Two collections with sharp edges — sets for uniqueness and fast membership, tuples for values that must not change.
In this lesson · 12 min
- →Use sets to deduplicate and to test membership quickly
- →Apply set algebra — union, intersection, difference
- →Use tuples for fixed records and multiple return values
- →Choose the right collection for a job
You have met lists and dictionaries. Two more collections round out the set, each solving a problem the others handle badly.
Sets: unique, unordered
A set holds each value at most once and does not remember an order.
Membership is fast
Checking x in collection on a list scans every item. On a set it is effectively instant,
however large the set.
Changing a set
Sets are unordered, so there is no indexing and no .sort(). Convert to a list when you need
an order:
Set algebra
This is where sets stop being “a list without duplicates” and start being genuinely useful.
That last check — intersecting your train and test ids — is a real data-leakage test you should run on every dataset you split.
Tuples: fixed, ordered
A tuple is an ordered sequence like a list, but it cannot be changed after it is created.
Duplicates are fine — a tuple is a sequence, not a set:
Working around immutability
You do not modify a tuple; you build a new one.
Why tuples exist
Unpacking. Assign several names at once:
Multiple return values. A function returning a tuple looks like it returns several things:
Dictionary keys. Because a tuple cannot change, it can be hashed — so it can be a key. A list cannot.
Choosing between them
| Need | Use |
|---|---|
| An ordered collection you will change | list |
| A fixed record, or several return values | tuple |
| Uniqueness, or fast membership tests | set |
| Lookup by a meaningful key | dict |
Try it yourself
Print the number of document ids that appear in both splits, as overlap: N.
Unpack record into name, score and latency in one statement.
Check yourself
Which of these can be used as a dictionary key?
Recap
- Sets hold unique values, have no order, and test membership in constant time.
|,&,-and^give you union, intersection, difference and symmetric difference.{}is an empty dict; useset()for an empty set.- Tuples are immutable sequences — ideal for fixed records, unpacking and dictionary keys.
- Unpacking (
a, b = pair) is how Python functions return more than one value.