Python Tuple and Set Exercises: Fixed Records and Unique Values
Tuples and sets solve two different problems: keeping a fixed record, and keeping only unique values. Practice choosing between them instead of defaulting to a list.
Unpack a record into names
A tuple is a good fit for a small fixed record. Unpacking gives each field a name and makes the next line read like a sentence. The number of names must match the number of values.
item = ("latte", 4.5)
name, price = item
print(f"{name}: ${price:.2f}")A named record
Treat a tuple as immutable
You cannot append to a tuple or replace one of its positions. Build a new tuple when a value changes. That constraint is useful when a record should not be modified by accident.
point = (3, 5)
shifted = (point[0] + 1, point[1] + 1)
print(shifted)Create a new tuple
Deduplicate without preserving order
set(values) keeps one copy of each value. Use len(set(values)) to count distinct items. If you need the original order, a set alone is not enough; keep a seen set while building a new list.
orders = ["latte", "tea", "latte", "mocha"]
unique = set(orders)
print(len(unique))Count distinct values
Use membership and set operations
Membership with in is fast and readable. Intersection and union answer questions about overlap and combined values. Sort the result before printing when you need a stable display.
a = {"latte", "tea"}
b = {"tea", "mocha"}
print(sorted(a & b))
print(sorted(a | b))Overlap and union
Choose the collection deliberately
Use a list when order and duplicates matter. Use a tuple for a fixed record. Use a set for uniqueness or membership. Naming the question first usually makes the choice obvious.
orders = ["latte", "tea", "latte"]
print(orders[0])
print(len(set(orders)))Position versus uniqueness
Your practice checklist
- Use parentheses and commas for a tuple.
- Unpack only when the field count is known.
- Use a set to count distinct values.
- Sort a set before printing when order matters.
Common questions
Can a tuple contain a list?
Yes. The tuple itself is immutable, but a mutable object inside it can still change. That is usually a sign that the data should be modelled differently.
Why is set order different between runs?
Sets are unordered collections. Do not rely on their display order; sort the values or build an ordered list when order matters.
How do I remove duplicates but keep order?
Walk the original list, add each new value to a seen set, and append it to a result list only when it is not already seen.
Practice tuples and sets
12 questions on unpacking, deduplication, membership, and set operations.
Keep reading: