Tuples & Sets
Tuples: ordered and unchangeable
point = (3, 4)
- Use tuples for fixed groups of values: coordinates, RGB colours, database rows.
- They can be dictionary keys (lists can't).
- Unpacking:
x, y = point, andfirst, *rest = (1, 2, 3). - A one-item tuple needs a comma:
(5,).(5)is just the number 5.
Sets: unique values, no order
tags = {"python", "sql"}
- Duplicates are removed automatically, so
set([1, 1, 2])→{1, 2}. - Checking
x in my_setis very fast, much faster than in a list for big data. - An empty set is
set(), because{}is an empty dict.
Set operations
| Operator | Meaning |
|---|---|
a | b | union (in either) |
a & b | intersection (in both) |
a - b | difference (in a, not b) |
a ^ b | in one but not both |
💡 list(dict.fromkeys(items)) removes duplicates and keeps the order.
▶️ Runs in the app.
Example
point = (3, 4)
x, y = point
print(x, y) # 3 4
first, *rest = (1, 2, 3, 4)
print(first, rest) # 1 [2, 3, 4]
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # {1, 2, 3, 4}
print(a & b) # {2, 3}
print(a - b) # {1}
emails = ["a@x.com", "b@x.com", "a@x.com"]
print(len(set(emails))) # 2 unique
print(list(dict.fromkeys(emails))) # ['a@x.com', 'b@x.com']