LearnPy Hub
Data StructuresBeginnerLesson 10 of 32

Tuples & Sets

Watch the ideaTuples stay fixed, sets stay unique
point = (3, 5)
point (tuple)
30
51

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 colours is 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

OperationSymbolMeaning
uniona | beverything in either
intersectiona & bonly what's in both
differencea - bin a but not in b
symmetric differencea ^ bin 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.

Step-by-step

Try it yourselfExample 1: Tuples and unpacking

Tuples group related values. Unpacking gives each one a name.

example_1.py
Output appears here
Fill in the blanks

Unpack a point

Fill the blanks so the tuple is unpacked into x and y and the program prints 3 7.

blanks.py
point = (3, 7)
,  = point
print(x, y)

Example 2: Tuples can't change

Remove the

example_2.py
Output appears here
Fix the bug

Changing a tuple

This should change the first colour to blue and print ('blue', 'green'), but it crashes. Fix it by using a list.

buggy.py

Example 3: Removing duplicates with a set

sorted() turns the set back into an ordered list for printing.

example_3.py
Output appears here
Fill in the blanks

Unique visitors

Fill the blank so duplicates disappear and the program prints how many different names there are: 3.

blanks.py
names = ["Ana", "Bo", "Ana", "Cy", "Bo"]
print(len((names)))

Example 4: Comparing groups

Who joined both clubs? Who joined only one?

example_4.py
Output appears here
Your turn

Friends 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'].

my_code.py
Your turn

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)

my_code.py

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.

Step-by-step

Example 5: Star unpacking and tuples in a set

Tuples can go inside a set because they never change.

example_5.py
Output appears here

Example 6: Set methods in action

discard is safe on missing items; remove isn't.

example_6.py
Output appears here

3Level 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.

example_7.py
Output appears here

Example 8: frozenset pairs and what's hashable

The pair {Mina, Raju} counts once, whichever way round it is written. Remove the

example_8.py
Output appears here
Gotcha{} 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.
Exercise · predict the output

What does this print?

print(len({1, 2, 2, 3, 3, 3}))
Quick quiz · 5 questions
1. Which of these can't be changed after it's created?
2. What does {1, 2, 3} & {2, 3, 4} give?
3. How do you create an empty set?
4. After x, y = (8, 2), what is y?
5. Why might you turn a list into a set?
Ready to practice tuples & sets?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Tuples & Sets · LearnPy Hub