Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Unpacking & Iterable Patterns
Unpacking lets you assign multiple values at once. Python supports extended unpacking with * for splitting sequences.
Unpacking
# Basic unpacking
a, b, c = [1, 2, 3]
print(a, b, c)
# Swap
x, y = 10, 20
x, y = y, x
print(x, y) # 20, 10
# Extended unpacking with *
first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last) # 1 [2, 3, 4] 5
head, *tail = [1, 2, 3, 4]
print(head) # 1
print(tail) # [2, 3, 4]
# Ignoring values with _
_, name, _ = ("id1", "Alice", "extra")
print(name) # Alice
# Unpacking in loops
pairs = [(1, "a"), (2, "b"), (3, "c")]
for num, letter in pairs:
print(f"{num}: {letter}")
# Dictionary unpacking
config = {"host": "localhost", "port": 8080}
host, port = config.values()
print(f"{host}:{port}")Tip
Tip
Use * for extended unpacking: first, *rest = [1,2,3,4,5] gives first=1, rest=[2,3,4,5]. Use _ for values you don't need.
Destructuring lets you unpack object properties and array elements in one line
Common Mistake
Warning
Unpacking must match the number of values. a, b = [1,2,3] raises ValueError. Use a, b, *_ = [1,2,3] to ignore extras.
Practice Task
Note
(1) Unpack first, *middle, last from a list. (2) Swap two variables. (3) Iterate (key, value) pairs. (4) Use _ to ignore unwanted values.