These are the notes for Python episode 11. Last episode we invented the list, and its superpower was change. Today that superpower causes two problems. A shop's location gets changed by one careless line, so we invent the tuple, a list that can't change. Then counting unique customers with a list gets painfully slow, so we invent the set, a collection with no duplicates and instant lookups. You will learn tuple syntax, unpacking and the one-line swap, the one-item tuple trap, lists of tuples, set(), add, remove, discard, why sets have no order or indexes, union, intersection and difference, and the {} trap. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.
Problem 1: a location that changed by mistake
Raju starts home delivery. His shop's location is two numbers: latitude and longitude. Stored as a list:
shop = [28.61, 77.21]
print("Deliver to:", shop)
# ... 500 lines later ...
shop[0] = 0
print("Deliver to:", shop)
Output:
Deliver to: [28.61, 77.21]
Deliver to: [0, 77.21]
No error, no warning. Why: a list is mutable, so any line anywhere can change it. Great for a shopping list, a trap for data that must never change.
Tuples: locked data
| In real life | In Python |
|---|---|
| A notebook page: write, erase, rewrite | a list [28.61, 77.21]: mutable |
| A printed train ticket: read it any time, never edit it | a tuple (28.61, 77.21): immutable |
A tuple is an ordered collection like a list, written with round brackets, that can never change after it's made.
shop = (28.61, 77.21)
print(shop[0], len(shop))
shop[0] = 0
Output:
28.61 2
Traceback (most recent call last):
File "main.py", line 3, in <module>
shop[0] = 0
~~~~^^^
TypeError: 'tuple' object does not support item assignment
Reading works exactly like a list (indexes, negative indexes, slices, len, in, loops). Changing is an error, and that's a good error: the mistake is caught on the exact line where it happens.
Tuples have only two methods, because they can't change:
t = (3, 1, 3, 2, 3)
print(t.count(3), t.index(2))
Output:
3 3
count(3): 3 appears 3 times. index(2): the first 2 is at index 3.
Unpacking and the swap
Unpacking puts each value of a tuple into its own variable:
shop = (28.61, 77.21)
lat, lon = shop
print("Latitude:", lat)
print("Longitude:", lon)
a, b = 5, 9
a, b = b, a
print(a, b)
Output:
Latitude: 28.61
Longitude: 77.21
9 5
a, b = b, a swaps two variables in one line: the right side builds the tuple (9, 5), and the left side unpacks it. Most other languages need a third, temporary variable.
Trap 1: the one-item tuple
one = (5)
print(type(one))
one = (5,)
print(type(one))
Output:
<class 'int'>
<class 'tuple'>
Brackets alone are just maths brackets. The comma makes a tuple. An empty tuple is ().
Trap 2: unpacking needs matching counts
x, y = (1, 2, 3)
Output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
x, y = (1, 2, 3)
^^^^
ValueError: too many values to unpack (expected 2)
Three values, two names. Use x, y, z = (1, 2, 3).
A menu of tuples
Tuples shine for fixed records: values that belong together. Each menu item is a (name, price) tuple; the menu itself is a list, because it can grow.
menu = [("Chai", 10), ("Samosa", 15), ("Vada pav", 20)]
for item, price in menu:
print(item, "costs Rs", price)
Output:
Chai costs Rs 10
Samosa costs Rs 15
Vada pav costs Rs 20
The loop unpacks each pair as it goes. A list of tuples is one of the most common shapes of data in Python (rows of a table, points on a map, results from a database).
Problem 2: counting unique customers
Raju logs every loyalty-card visit in a list. len(visits) counts visits, not people. The obvious fix, a list of names seen so far:
visits = ["Asha", "Ravi", "Asha", "Meena", "Ravi", "Asha"]
print("Visits:", len(visits))
unique = []
for v in visits:
if v not in unique:
unique.append(v)
print("Customers:", len(unique))
Output:
Visits: 6
Customers: 3
Correct for six visits. Now a year: 50,000 card IDs, each swiped twice:
visits = list(range(50000)) * 2 # card IDs
unique = []
for v in visits:
if v not in unique:
unique.append(v)
print("Customers:", len(unique))
Result in the SyntaxPilot compiler: Time Limit Exceeded (it takes about 14 seconds on a normal computer).
Why: in on a list checks the items one by one from the start. When unique has 50,000 items, each of the 100,000 visits checks up to 50,000 names: billions of checks.
Sets: no duplicates, instant lookups
| At a wedding gate | In Python |
|---|---|
| A guest walks in; the guard ticks the name | guests.add("Asha") |
| Asha steps out and comes back in: already ticked | a set never stores a duplicate |
| "Is Ravi here?" The guard finds it in one look | "Ravi" in guests is instant |
A set is an unordered collection of unique items, written with curly brackets. It's built for lookups: instead of checking items one by one, it files each item by a code computed from its value (a hash), so in jumps straight to it.
visits = list(range(50000)) * 2 # card IDs
unique = set(visits)
print("Customers:", len(unique))
Output (in a blink):
Customers: 50000
With names:
visits = ["Asha", "Ravi", "Asha", "Meena", "Ravi", "Asha"]
unique = set(visits)
print(len(visits), len(unique))
print(sorted(unique))
Output:
6 3
['Asha', 'Meena', 'Ravi']
set(list) removes duplicates. We print sorted(unique) because a set has no order of its own (see below).
Changing a set
ids = {101, 102, 103}
ids.add(104)
ids.add(101)
print(ids)
ids.discard(999)
ids.remove(102)
print(ids)
print(103 in ids)
Output:
{104, 101, 102, 103}
{104, 101, 103}
True
add(x)adds an item; adding one that's already there does nothing.- 104 printed first: a set has no order. Don't rely on how it prints (with strings the order can even change between runs).
discard(x)removesxif it's there and stays quiet if not.remove(x)removesxand raises an error if it's missing:
ids = {101, 102, 103}
ids.remove(999)
Output:
Traceback (most recent call last):
File "main.py", line 2, in <module>
ids.remove(999)
~~~~~~~~~~^^^^^
KeyError: 999
No indexes
ids = {101, 102, 103}
print(ids[0])
Output:
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(ids[0])
~~~^^^
TypeError: 'set' object is not subscriptable
Subscriptable means you can use square brackets with a position. A set has no positions. Need one? sorted(ids)[0] or list(ids).
Set maths: both, either, only
mon = {"Asha", "Ravi", "Meena", "Kiran"}
tue = {"Ravi", "Kiran", "Sunil"}
print("Both days:", sorted(mon & tue))
print("Either day:", sorted(mon | tue))
print("Only Monday:", sorted(mon - tue))
Output:
Both days: ['Kiran', 'Ravi']
Either day: ['Asha', 'Kiran', 'Meena', 'Ravi', 'Sunil']
Only Monday: ['Asha', 'Meena']
| Operator | Method | Name | Question it answers |
|---|---|---|---|
a & b |
a.intersection(b) |
intersection | in both |
a | b |
a.union(b) |
union | in either (everything) |
a - b |
a.difference(b) |
difference | in a only |
a ^ b |
a.symmetric_difference(b) |
symmetric difference | in exactly one of them |
a <= b |
a.issubset(b) |
subset | is everything in a also in b? |
Picture two overlapping circles: & is the overlap, | is everything, - is one circle without the overlap.
The {} trap
empty = {}
print(type(empty))
empty = set()
print(type(empty))
Output:
<class 'dict'>
<class 'set'>
Empty curly brackets make a dictionary (next episode). An empty set is set().
List vs tuple vs set
List [ ] |
Tuple ( ) |
Set { } |
|
|---|---|---|---|
| Ordered (has indexes) | yes | yes | no |
| Can change | yes | no | yes (add/remove) |
| Duplicates allowed | yes | yes | no |
x in ... speed |
checks one by one | checks one by one | instant |
| Use for | a growing collection | a fixed record | unique items, membership, both/either/only |
| Empty | [] |
() |
set() |
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
shop[0] = 0 on a list |
no error, data silently changed | lists are mutable | use a tuple for fixed data |
shop[0] = 0 on a tuple |
TypeError: 'tuple' object does not support item assignment |
tuples are immutable | make a new tuple |
one = (5) |
no error, it's an int |
brackets alone aren't a tuple | (5,) |
x, y = (1, 2, 3) |
ValueError: too many values to unpack (expected 2) |
3 values, 2 names | match the counts |
| removing duplicates with a list loop on big data | Time Limit Exceeded | in on a list checks every item |
set(list) |
ids.remove(999) |
KeyError: 999 |
the item isn't in the set | ids.discard(999) |
ids[0] |
TypeError: 'set' object is not subscriptable |
sets have no positions | sorted(ids)[0] |
empty = {} for a set |
no error, it's a dict |
{} is an empty dictionary |
set() |
Mini project: the combo-offer finder
Two visit logs (with repeats): chai buyers and samosa buyers. Find the number of customers, who gets a combo offer (bought both), and who gets a suggestion for the other item.
# Mini project: combo-offer finder
chai = ["Asha", "Ravi", "Meena", "Asha", "Kiran", "Ravi"]
samosa = ["Ravi", "Sunil", "Kiran", "Sunil", "Tara"]
chai_set = set(chai)
samosa_set = set(samosa)
print("Customers:", len(chai_set | samosa_set))
print("Combo offer for:", sorted(chai_set & samosa_set))
print("Only chai:", sorted(chai_set - samosa_set))
print("Only samosa:", sorted(samosa_set - chai_set))
Output:
Customers: 6
Combo offer for: ['Kiran', 'Ravi']
Only chai: ['Asha', 'Meena']
Only samosa: ['Sunil', 'Tara']
Extend it: add a vada pav log and find who bought all three.
Solution
chai = {"Asha", "Ravi", "Kiran"}
samosa = {"Ravi", "Kiran", "Sunil"}
vada = {"Kiran", "Tara", "Ravi"}
print(sorted(chai & samosa & vada))
Output:
['Kiran', 'Ravi']
Practice
1. Store three dates as (day, month, year) tuples in a list and print each one unpacked.
Solution
dates = [(5, 11, 2026), (26, 1, 1950), (15, 8, 1947)]
for day, month, year in dates:
print("Day", day, "of month", month, "in", year)
Output:
Day 5 of month 11 in 2026
Day 26 of month 1 in 1950
Day 15 of month 8 in 1947
2. Print how many unique words a list has, and the words in alphabetical order.
Solution
words = ["chai", "samosa", "chai", "lassi", "samosa", "chai", "poha", "lassi"]
unique = set(words)
print(len(unique), sorted(unique))
Output:
4 ['chai', 'lassi', 'poha', 'samosa']
3. Two friends' hobbies: print the shared ones, the ones only Asha has, and the ones that aren't shared.
Solution
asha = {"cricket", "music", "chess"}
ravi = {"chess", "movies", "cricket", "cooking"}
print("Shared:", sorted(asha & ravi))
print("Only Asha:", sorted(asha - ravi))
print("Not shared:", sorted(asha ^ ravi))
Output:
Shared: ['chess', 'cricket']
Only Asha: ['music']
Not shared: ['cooking', 'movies', 'music']
4. Print every number that appears again in a list, the moment it repeats.
Solution
nums = [3, 1, 3, 2, 1]
seen = set()
for n in nums:
if n in seen:
print("Repeated:", n)
seen.add(n)
Output:
Repeated: 3
Repeated: 1
A set of "seen" items is a classic pattern: each in check is instant.
Quick quiz
names = ["a", "b", "a", "c", "b"]
print(len(set(names)))
What does it print? 5, 3, 2, or TypeError?
Answer
3. The set keeps "a", "b" and "c" once each.
Interview questions
- List vs tuple? Both are ordered and indexable; a list is mutable, a tuple is immutable. Use a tuple for fixed records, and when you need something that can be a dictionary key.
- How do you remove duplicates from a list?
set(lst)(loses the order) orlist(dict.fromkeys(lst))(keeps the first-seen order:[3, 1, 3, 2]→[3, 1, 2]). - Why is
x in my_setfaster thanx in my_list? A set stores items by their hash, so a lookup jumps straight to the right place; a list checks items one by one. - How do you write a one-item tuple? With a trailing comma:
(5,). - How do you swap two variables in Python?
a, b = b, a(tuple packing and unpacking). removevsdiscardon a set?removeraisesKeyErrorif the item is missing;discarddoes nothing.- How do you create an empty set?
set();{}is an empty dictionary.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Tuple | An ordered collection that can't be changed, in round brackets | (28.61, 77.21) |
| Immutable | Can't be changed after it's made | tuples, strings |
| Mutable | Can be changed after it's made | lists, sets |
| Latitude / longitude | The two numbers that give a place on Earth | 28.61, 77.21 |
| Record | A few values that belong together | ("Chai", 10) |
| Unpacking | Putting each value of a tuple into its own variable | lat, lon = shop |
| Swap | Exchanging two variables' values | a, b = b, a |
| Trailing comma | The comma that makes a one-item tuple | (5,) |
| Set | An unordered collection of unique items, in curly brackets | {101, 102} |
| Duplicate | The same value appearing more than once | "Asha" three times |
| Hash | A code computed from a value, used to file and find it fast | how sets and dicts look things up |
add / discard / remove |
Put in / take out quietly / take out or raise KeyError |
ids.add(104) |
KeyError |
The item (key) you asked to remove or read isn't there | ids.remove(999) |
| Subscriptable | Supports square brackets with a position | lists yes, sets no |
Union | |
Everything in either set | mon | tue |
Intersection & |
Only what's in both sets | mon & tue |
Difference - |
What's in the first set but not the second | mon - tue |
Symmetric difference ^ |
What's in exactly one of the sets | asha ^ ravi |
| Time Limit Exceeded | The compiler stopped a program that ran too long | the list-based dedupe |
Summary
- A tuple
( )is a list that can't change: read it with indexes, unpack it into names, use it for fixed records. Changing it is aTypeError. a, b = b, aswaps;(5,)needs the comma; unpacking needs matching counts.- A set
{ }keeps unique items with no order and instantinchecks.set(list)removes duplicates. add,discard(quiet),remove(KeyErrorif missing); no indexes.&both,|either,-only. An empty set isset(), because{}is a dict.
Next episode: dictionaries. Look up the price of samosa by its name, instantly, instead of searching a list.