Beginner·6 min·basics · tuples · sets
Tuples & Sets
You’ll be able to
- Choose between mutable lists, immutable tuples, and unique sets
- Unpack tuples into multiple variables in one line
- Perform set operations: union, intersection, difference
- Convert between list, tuple, and set as needed
Why this matters
Tuples are the default return type for multi-value functions (divmod, os.path.split) and the only hashable sequence, making them dict-key material. Sets solve dedup and membership tests in O(1), a favorite interview trick.
Common pitfalls
- Writing
t = (1)for a single-item tuple. That is anint; the correct form ist = (1,)with a trailing comma. - Trying to mutate a tuple:
t[0] = 5raisesTypeError. Convert withlist(t)if you need mutation. - Assuming sets preserve order. They do not; use
dict.fromkeys(lst)if you need order-preserving dedup.
Tuples
(1, 2, 3)— like a list, but immutable (can't change after creation)- Useful for fixed records:
point = (x, y),(name, age) - Unpacking:
a, b = (1, 2)is one of Python's loveliest features
Sets
{1, 2, 3}— unordered collection of unique values- O(1) membership check (much faster than a list for "is x in this?")
- Set algebra:
|union,&intersect,-difference
Try it
- Deduplicate a list with
list(set(items)). - Find words that appear in both
"the quick brown fox"and"the lazy dog".
Practice
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
Progress0 / 3
- Exercise 1
Given
point = (7, 24), unpack it into variablesxandy, then print exactlyx=7, y=24. - Exercise 2
The list
items = ["a", "b", "a", "c", "b", "d"]has duplicates. Print how many unique values it has — expected:4. - Exercise 3
Given two sets of skills,
me = {"python", "sql", "docker"}andjob = {"python", "aws", "docker"}, print the sorted list of shared skills — expected:['docker', 'python'].