Python Tutorial
Python Assign Multiple Values
Python can unpack several values into several variables in one statement.
Many Values to Multiple Variables
The number of variables must match the number of values.
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)One Value to Multiple Variables
You can assign the same value to several names.
x = y = z = "Orange"
print(x, y, z)Unpack a Collection
Extract values from a list or tuple into variables.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(z)📘 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
A log-line parser that extracts the timestamp, level, and message from each line.
Real-Life Example
import re
from collections import Counter
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<msg>.*)$"
)
levels = Counter()
with open("app.log") as f:
for line in f:
m = LINE.match(line)
if not m:
continue
ts, level, msg = m["ts"], m["level"], m["msg"]
levels[level] += 1
if level == "ERROR" and "timeout" in msg:
print(ts, "→", msg)
print(dict(levels))Expected Output
{"INFO": 187, "WARN": 14, "ERROR": 3}Common mistakes
- Unpacking a tuple of the wrong size raises
ValueError— wrap risky unpacks intry/exceptor use starred capture (a, *rest, b = seq). - Unpacking nested structures forces every level to match — flatten early when shapes vary.
- Forgetting parentheses around a tuple of one element (
x = 1,) is legal Python and frequently surprising.
🚀 Performance & Best Practices
- Starred-unpacking (
*a, b = seq) is O(n) in CPython — fine for tens of items, use a slice otherwise. - Bulk initialisation:
x = y = z = 0rebinds the same object; if it's mutable, all names refer to one list. - For large dicts, unpack with
**d1, **d2instead of nested unpacking.
🧪 Try It Yourself
- Extend the regex to capture the request ID and count requests per minute.
- Refactor the example to use
match.groupdict()directly without unpacking. - Star-unpack a 100-element list into
first, *middle, lastand measure the overhead vs. indexing.