Tuples & Sets
point = (3, 5)A tuple is an ordered row that can't be changed after it's made.
1Level 1 · BasicsBasics
Lists aren't the only collections. Tuples are like lists that can't change, and sets are collections with no duplicates and no order. Choosing the right one makes code simpler and faster.
Tuples: fixed groups of values
point = (3, 4) rgb = (255, 128, 0) single = (5,) # a one-item tuple needs the comma
Tuples use round brackets. You can index and slice them like lists, but you can't change them: point[0] = 10 is an error. Use a tuple for things that belong together and shouldn't change, like coordinates, a date, or an RGB colour.
Unpacking
You can split a tuple into variables in one step. You've already used this with a, b = b, a!
x, y = point # x = 3, y = 4
name, age = ("Mim", 19)
Functions often return tuples, for example divmod(17, 5) returns (3, 2).
Sets: unique items
colours = {"red", "green", "red", "blue"}
print(colours) # {'red', 'green', 'blue'} (in some order)
A set keeps each value once and has no order, so you can't index it. Sets are perfect for:
- Removing duplicates:
set([1, 2, 2, 3])gives{1, 2, 3}. - Fast membership tests:
"red" in coloursis very quick, even for huge sets. - Comparing groups with set maths (below).
Add with s.add(x) and remove with s.discard(x). An empty set is set(), because {} makes an empty dictionary.
Set operations
| Operation | Symbol | Meaning |
|---|---|---|
| union | a | b | everything in either |
| intersection | a & b | only what's in both |
| difference | a - b | in a but not in b |
| symmetric difference | a ^ b | in exactly one of them |
Key points: tuples are ordered and unchangeable; unpacking assigns several variables at once; sets hold unique, unordered items; use set operations to compare groups.
See it in actionTuples unpack, sets keep one of each
The set only grows when a new letter appears.
Try it yourselfExample 1: Tuples and unpacking
Tuples group related values. Unpacking gives each one a name.
Output appears hereUnpack a point
Fill the blanks so the tuple is unpacked into x and y and the program prints 3 7.
point = (3, 7) , = point print(x, y)
Example 2: Tuples can't change
Remove the
Output appears hereChanging a tuple
This should change the first colour to blue and print ('blue', 'green'), but it crashes. Fix it by using a list.
Example 3: Removing duplicates with a set
sorted() turns the set back into an ordered list for printing.
Output appears hereUnique visitors
Fill the blank so duplicates disappear and the program prints how many different names there are: 3.
names = ["Ana", "Bo", "Ana", "Cy", "Bo"] print(len((names)))
Example 4: Comparing groups
Who joined both clubs? Who joined only one?
Output appears hereFriends in both clubs
Club A has {"Mim", "Rafi", "Tara"} and club B has {"Tara", "Joy", "Mim"}. Print the names in both clubs, sorted: ['Mim', 'Tara'].
Return two values
Read numbers on one line. Put the smallest and largest into a tuple and print it, like (1, 9) for 4 9 1.
Example input4 9 1Expected output(1, 9)
2Level 2 · IntermediateTuples as records, sets for fast checks
Tuples inside sets
Because tuples can't change, they can be set items: {(23.8, 90.4), (22.4, 91.8)} is a set of map points. A list can't. (In the next lesson they become dictionary keys too.)
Star unpacking
first, *middle, last = scores grabs the ends and collects the rest into a list.
Set methods
add, discard (no error if missing), remove (error if missing), issubset, isdisjoint. A loop with add() builds a set item by item.
Why sets are fast
A set uses hashing, so x in s takes about the same time with 10 items or 10 million. For "have I seen this?" questions, always reach for a set.
See it in actionSeen-before with a set
Watch the seen set grow; the first repeat stops the loop.
Example 5: Star unpacking and tuples in a set
Tuples can go inside a set because they never change.
Output appears hereExample 6: Set methods in action
discard is safe on missing items; remove isn't.
Output appears here3Level 3 · AdvancedTuple records, frozenset and hashing
Tuples as records
A tuple like (4.8, "Mina", 3) is a small record. A list of them sorts field by field, so put the field you want to sort by first. (Later, collections.namedtuple lets you name the fields.)
frozenset
An unchangeable set. Because it's hashable, it can go inside another set: useful for "the same group regardless of order", like a pair of friends.
What hashable means
An object is hashable if its value can't change; Python turns it into a number (hash()) to find it quickly. Numbers, strings, tuples of hashable things and frozensets are hashable. Lists and sets are not.
Symmetric difference
a ^ b keeps items in exactly one of the two sets: perfect for "what changed between yesterday and today?".
Example 7: Records as tuples
GPA comes first in each tuple, so sorting puts the highest GPA on top.
Output appears hereExample 8: frozenset pairs and what's hashable
The pair {Mina, Raju} counts once, whichever way round it is written. Remove the
Output appears here{} creates an empty dictionary, not an empty set. Use set(). And a one-item tuple needs a trailing comma: (5,), because (5) is just the number 5.What does this print?
print(len({1, 2, 2, 3, 3, 3}))50 graded problems are waiting in Topic Practice.