Python Tutorial
Python Unpack Tuples
When you create a tuple, you pack values. Unpacking assigns those values to variables.
Unpacking
The number of variables must match the number of values, unless you use *.
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)Using Asterisk *
Collect leftover values into a list.
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)📘 Real-World Deep Dive
Tuple-unpacking on assignment is one of Python's most expressive features. It turns "swap two values", "split a URL", and "iterate key/value pairs" into one-liners that read almost like English.
Real-Life Scenario
Iterating over a small CSV-style log and immediately unpacking each line into a structural record — with star-unpack to absorb the variable-length "rest".
Real-Life Example
import re
LINE = re.compile(
r"^(?P<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) "
r"(?P<level>INFO|WARN|ERROR) "
r"(?P<kind>\S+) "
r"(?P<rest>.*)$"
)
records: list[tuple[str, str, str, str]] = []
with open("app.log") as f:
for line in f:
if m := LINE.match(line):
ts, level, kind, *rest_words = m["ts"], m["level"], m["kind"], *(m["rest"].split())
rest = " ".join(rest_words)
records.append((ts, level, kind, rest))
print("total records:", len(records))
for r in records[:3]:
print(":", r)Expected Output
total records: 187
: ('2026-08-20 09:01:02', 'INFO', 'http.GET', '/users/42')
: ('2026-08-20 09:01:02', 'INFO', 'db.query', 'SELECT * FROM users WHERE id=42')
: ('2026-08-20 09:01:03', 'WARN', 'cache.miss', 'users:42')Common mistakes
- Unpacking a tuple of the wrong size raises
ValueError— wrap risky unpacks intry/exceptor use star capture. - Star-unpack aggressively
*a, b = seqcreates a list of length n-1 — fine for small, large for huge. - Unpacking
(a, b) = (a, b)is the canonical swap — don't write it astmp = a; a = b; b = tmp.
🚀 Performance & Best Practices
- Use star-unpack for variable structure, slicing for known lengths — slicing copies; star-unpack allocates.
- Tuple-unpacking is the fastest way to assign multiple values at once.
- Avoid nested unpacking past 2 deep; flatten manually.
🧪 Try It Yourself
- Star-unpack a user-agent string like
"Mozilla/5.0 (X11; Linux) ..."into platform + comment. - Parse a ULID-style
"01HXYZ...."into timestamp + randomness. - Refactor the example to use
match.groupdict()directly.