Coding Techniques
Tuples · Study material
zip() builds tuples; zip(*pairs) takes them apart
zip pairs items from several sequences as tuples. Spreading the pairs back into zip with * transposes them – the classic "unzip".
names = ("Asha", "Ravi", "Meera")
marks = (91, 78, 85)
pairs = list(zip(names, marks)) # zip builds tuples
print(pairs)
n, m = zip(*pairs) # "unzip": * spreads the pairs as arguments
print(n, m)
lookup = dict(pairs) # pairs → dict
print(lookup["Meera"])
[('Asha', 91), ('Ravi', 78), ('Meera', 85)]
('Asha', 'Ravi', 'Meera') (91, 78, 85)
85Tuple or list?
| Use a tuple when… | Use a list when… |
|---|---|
| the items form one record: (name, age, city) | the items are many things of the same kind |
| the size is fixed | items are added or removed |
| it must be a dict key or set item | you need sort(), append(), remove() |
| you return several values from a function | you build results in a loop |
Safe unpacking patterns
line = "Asha,21,CSE,Pune"
name, age, *rest = line.split(",") # tolerates extra fields
first, _, third, _ = line.split(",") # _ for values you ignore
row = ("Ravi", 78)
if len(row) == 2: # check the shape when input is untrusted
name, marks = row Tuples checklist
- Always add the comma for one-item tuples.
- Unpack instead of indexing: name, age = row.
- Use a starred name when the length can vary.
- Use namedtuple (or a dataclass) for readable records.
- Keep only immutable items in tuples used as keys.
- Convert with tuple(sorted(t)) when you need a sorted tuple.