Tuples and Sets — When and Why
Lists are the general-purpose container. But two specialized cousins solve specific problems better: tuples (unchangeable sequences) and sets (uniqueness machines).
Tuples: lists that took a vow
A tuple is a list that can never change — same syntax, round brackets:
coordinates = (28.6139, 77.2090) # Delhi's location
rgb = (255, 128, 0)
date_of_birth = ("2009", "August", "15")Everything you know about lists works: indexing, slicing, len(), in, loops:
print(coordinates[0]) # 28.6139
print(rgb[-1]) # 0
lat, lng = coordinates # UNPACKING — a tuple superpower!
print(lat, lng) # 28.6139 77.2090That unpacking move is everywhere — you already used it: left, right = st.columns(2) returns a tuple, and you unpacked it.
Why tuples exist (the point of "unchangeable")
coordinates[0] = 40 # TypeError: 'tuple' object does not support item assignmentThat restriction is a feature. Use a tuple when the data is a fixed unit:
return lat, lng — that's a tuple!)If code tries to modify it, Python crashes loudly — protecting data that shouldn't change. Lists say "edit me"; tuples say "I am what I am."
Sets: automatic uniqueness
A set is an unordered collection where every value appears at most once:
visited = {"Delhi", "Mumbai", "Delhi", "Goa", "Mumbai"}
print(visited) # {'Delhi', 'Mumbai', 'Goa'} — duplicates vanished!Curly brackets, no keys (that's a dict you'll meet next lesson), duplicates silently dropped.
The killer use case: deduplication
votes = ["Aarav", "Diya", "Aarav", "Kabir", "Diya", "Aarav"]
unique_voters = set(votes)
print(len(votes), "votes,", len(unique_voters), "unique voters")
# 6 votes, 3 unique voters
print(list(unique_voters)) # back to a list if you need oneOne conversion, every duplicate gone. Doing this manually with loops takes ten lines.
Set operations — the math you'll actually use
python_devs = {"Aarav", "Diya", "Kabir"}
js_devs = {"Diya", "Rohan"}
print(python_devs | js_devs) # union: everyone {'Aarav','Diya','Kabir','Rohan'}
print(python_devs & js_devs) # intersection: in BOTH {'Diya'}
print(python_devs - js_devs) # difference: only python {'Aarav', 'Kabir'}
print("Diya" in python_devs) # True — membership (very fast!)Union, overlap, and "who's only in this group" — real questions, one symbol each.
The fast membership secret
big_list = list(range(1_000_000))
big_set = set(big_list)
# 999999 in big_list → scans one by one... slow
# 999999 in big_set → jumps almost instantly... fastSets check membership dramatically faster than lists. When you need "have I seen this before?" on lots of data — set, not list.
Common Errors & Fixes
my_list = list(my_tuple).set(). Classic trap.s[0] fails); convert to a list if order matters.✅ Checkpoint
set([1, 1, 2, 3, 3]) gives? *({1, 2, 3})*lat, lng = (28.6, 77.2) — what's this called? *(Unpacking)*Next: dictionaries — the container that runs the internet.