Chapter 3 · Junior Developer

Tuples, sets and unpacking

Two more core collections, each with a specialty.

A tuple is like a list but immutable — once made, you can't change it: point = (3, 4). That fixedness makes tuples right for things that shouldn't change (coordinates, a row of fields) and lets them be used as dict keys. Their everyday superpower is unpacking: x, y = point pulls the two values into two variables in one line — the same mechanism that lets a function return several values (return lo, hi) and the caller catch them (lo, hi = ...).

A set is an unordered collection of unique values: {1, 2, 3}. It can't contain duplicates and doesn't track order. That makes the fastest de-duplicate a one-liner: set(my_list) drops repeats, and sorted(set(my_list)) gives a clean, ordered list back.

Sets also do maths: a & b (intersection — in both), a | b (union — in either), a - b (difference — in a but not b). And x in some_set is very fast, even on huge sets.

Syntax

point = (3, 4)        # tuple — immutable
x, y = point          # unpacking: x=3, y=4
lo, hi = min_max(...) # catch several returned values

tags = {"a", "b", "b"}   # set — becomes {'a', 'b'}
set([1, 2, 2, 3])        # {1, 2, 3}  (de-duplicate)
a & b   # intersection (in both)
a | b   # union (in either)
a - b   # difference (in a, not b)

Worked examples

Tuple unpacking — including multi-value returns

def min_max(nums):
    return min(nums), max(nums)   # returns a tuple

lo, hi = min_max([5, 1, 9])       # unpack it
print(lo, hi)   # 1 9

point = (3, 4)
x, y = point
print(x, y)     # 3 4

De-duplicate with set(), then sort back to a list

tags = ["python", "api", "python", "cli"]
print(set(tags))           # {'python', 'api', 'cli'}  (order varies)
print(sorted(set(tags)))   # ['api', 'cli', 'python']  (clean + ordered)

Set maths: intersection, union, difference

a = {1, 2, 3}
b = {2, 3, 4}
print(a & b)   # {2, 3}     (in both)
print(a | b)   # {1, 2, 3, 4} (in either)
print(a - b)   # {1}        (in a, not b)

Common mistakes & gotchas

Tuples can't be changed

point = (3, 4); point[0] = 9 raises TypeError. To 'change' a tuple you build a new one. (A one-element tuple needs the trailing comma: (5,)(5) is just the number 5 in brackets.)

Sets are unordered — don't rely on order

Printing or iterating a set gives no guaranteed order, and there's no indexing (my_set[0] is a TypeError). If you need order, sort it into a list: sorted(my_set).

{} is an empty dict, not an empty set

{} makes an empty *dictionary*. For an empty set you must write set(). {1, 2} is a set, but the braces alone default to a dict.

Why it matters

Tuple unpacking is how Python returns more than one value and how you read coordinate-like data cleanly. Sets turn 'are these unique?', 'what's shared?', and 'is this one of them?' into fast one-liners — `sorted(set(...))` for de-duping and `&`/`|`/`-` for comparing collections are tools you'll reach for constantly.