Skip to main content

04. Iterable Unpacking

Python allows you to unpack iterables (lists, tuples, etc.) into variables. This leads to cleaner, more expressive code.


Basic Unpacking

point = (3, 4)
x, y = point
print(x, y) # 3 4

Using * for Extended Unpacking

numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(first, middle, last) # 1 [2, 3, 4] 5

Ignoring Values with _

person = ("Alice", 30, "Engineer")
name, _, profession = person
print(name, profession)

Nested Unpacking

data = ("Alice", (30, "Engineer"))
name, (age, job) = data
print(name, age, job)

Practice Challenge

Given a list of tuples representing coordinates, unpack them into variables and print as "x=..., y=...".

coords = [(1,2), (3,4), (5,6)]

Wrap-Up

  • Unpacking simplifies working with tuples and lists.
  • Use * for collecting extra values.
  • Use _ for ignored values.