Lesson 14 of 30
In progress
Tuples and sets: fixed records and uniqueness
Use tuples for fixed records and sets for uniqueness, unpack both, and know why (1) is not a tuple and {} is not a set.
Lists and dictionaries cover most work, but two smaller collections solve two specific problems better: a group of values that must not change, and a collection where duplicates are meaningless.
What you will learn
- Create tuples, unpack them, and use them as fixed records.
- Build sets, remove duplicates and compare groups.
- Choose between a list, tuple, dictionary and set.
A tuple is a record that cannot change
A tuple is written with commas, usually inside brackets. Once created, its length and items are fixed.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(point)
print(point[0])
print(rgb)
print(len(single))
Press Run to see the output.
rgb shows that the brackets are optional; the commas make the tuple. The trailing comma in single is essential: (42) is just the number 42 in brackets, while (42,) is a one-item tuple. That is a genuine gotcha and worth a mental note.
Immutability means you cannot assign to an index, append or remove. It also means a tuple can be a dictionary key, and that two tuples with the same contents compare equal regardless of where they were created.
Unpacking is the everyday use
A tuple lets one name hold several related values, and unpacking gives each value its own name.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def min_max(values):
return min(values), max(values)
low, high = min_max([3, 9, 2])
print(low, high)
Press Run to see the output.
That function returns a tuple without saying so. Callers can unpack it, or keep it as one value. This is how Python returns several results without a special mechanism, and it is why you will see tuples in function signatures later in the track.
Use a tuple for a coordinate, an RGB colour, a database row, or any record whose shape is fixed. Use a list when the number of items can change.
A set removes duplicates and answers "have I seen this"
A set is an unordered collection of unique values. Creating one from a list drops duplicates automatically.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(unique)
print(len(visits))
print(len(unique))
print("mei" in unique)
Press Run to see the output.
The printed order is not guaranteed, so never rely on it for output. Membership is fast even in a large set, because sets use hashing rather than scanning. If you find yourself writing if item in big_list inside a loop, converting big_list to a set once usually fixes the slowness.
Empty braces create a dictionary, not a set. Write set() for an empty set, and {} only when you mean a dictionary.
Comparing groups
Sets support the operations you would expect from a Venn diagram.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(python_devs | js_devs)
print(python_devs & js_devs)
print(python_devs – js_devs)
print(python_devs ^ js_devs)
Press Run to see the output.
| is union, & is intersection, - is difference, and ^ is everything in one but not both. Named methods union, intersection, difference and symmetric_difference do the same work and read more clearly in long expressions.
Because sets are mutable, they cannot be dictionary keys or elements of another set. frozenset exists for that case and is rarely needed in beginner code.
values = {3, 1, 2} then values[0] raises TypeError: 'set' object is not subscriptable. Sets have no positions. If you need ordered access, convert with sorted(values), which returns a list.
Two classes submitted attendee lists with duplicates. Build a set from each, print who attended both classes, who attended only the first, and how many distinct people attended at all.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
morning_set = set(morning)
afternoon_set = set(afternoon)
print("Both:", morning_set & afternoon_set)
print("Morning only:", morning_set – afternoon_set)
print("Distinct people:", len(morning_set | afternoon_set))
Press Run to see the output.
The duplicates disappear when the sets are built, which is why the counts are correct without a separate de-duplication loop.
Which collection should I use?
| Need | Collection |
|---|---|
| Ordered items that change | list |
| A fixed record, or a dictionary key | tuple |
| Labelled values, lookup by name | dictionary |
| Uniqueness, fast membership, group maths | set |
Most beginner code needs lists and dictionaries. Reach for a tuple when the shape is fixed, and a set when duplicates are a bug rather than data.
Recap
- Tuples are immutable records; the comma makes the tuple, not the brackets.
- Unpacking turns a tuple into named values, including multiple return values.
- Sets remove duplicates, test membership quickly, and support union and intersection.
Next, you will combine these collections into nested structures, which is how real data actually arrives.
Why is (1) not a tuple?
Can I change a tuple by converting it to a list?
Progress is saved in this browser only. No account, no email.