Python Basics — Tuple Unpacking

2 minute read

Tuple Unpacking

Unpacking lets you assign each element of a tuple (or any iterable) to individual variables in a single statement. It’s one of Python’s most elegant features.

Basic Unpacking

coordinates = (10, 20)
x, y = coordinates

print(x)  # 10
print(y)  # 20

The number of variables must match the number of elements:

point = (1, 2, 3)

# ❌ Too few variables
# x, y = point  # ValueError: too many values to unpack

# ❌ Too many variables
# x, y, z, w = point  # ValueError: not enough values to unpack

# ✅ Exact match
x, y, z = point
print(x, y, z)  # 1 2 3

Star Unpacking (*)

Use * to capture remaining elements into a list:

first, *rest = (1, 2, 3, 4, 5)
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

*start, last = (1, 2, 3, 4, 5)
print(start)  # [1, 2, 3, 4]
print(last)   # 5

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

The starred variable always produces a list, even if it captures zero or one element.

first, *rest = (1,)
print(first)  # 1
print(rest)   # []  (empty list)

Swapping Variables

Python’s most famous unpacking trick — no temporary variable needed:

a = 10
b = 20

a, b = b, a

print(a)  # 20
print(b)  # 10

This works because the right side creates a tuple (b, a) first, then unpacks it.

Unpacking in for Loops

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

for x, y in points:
    print(f"x={x}, y={y}")
# x=1, y=2
# x=3, y=4
# x=5, y=6

With enumerate()

colors = ["red", "green", "blue"]

for i, color in enumerate(colors):
    print(f"{i}: {color}")
# 0: red
# 1: green
# 2: blue

With dict.items()

scores = {"Alice": 95, "Bob": 87, "Charlie": 92}

for name, score in scores.items():
    print(f"{name}: {score}")
# Alice: 95
# Bob: 87
# Charlie: 92

Ignoring Values with _

Use _ as a placeholder for values you don’t need:

record = ("Alice", 30, "alice@example.com", "555-1234")

name, _, email, _ = record
print(name)   # Alice
print(email)  # alice@example.com

Multiple values:

first, *_, last = (1, 2, 3, 4, 5)
print(first)  # 1
print(last)   # 5

_ is a valid variable name — it just signals “I don’t care about this value.”

Nested Unpacking

data = ("Alice", (95, 87, 92))
name, (score1, score2, score3) = data

print(name)    # Alice
print(score1)  # 95
print(score2)  # 87
print(score3)  # 92

Unpacking Function Return Values

Functions commonly return tuples for multiple return values:

def get_user():
    return "Alice", 30, "alice@example.com"

name, age, email = get_user()
print(name)   # Alice
print(age)    # 30
print(email)  # alice@example.com

# Or keep as tuple
user = get_user()
print(user)   # ('Alice', 30, 'alice@example.com')

Practical Example — Parsing Data

log_entries = [
    ("2025-01-15", "INFO", "Server started"),
    ("2025-01-15", "ERROR", "Connection timeout"),
    ("2025-01-16", "INFO", "Request processed"),
]

for date, level, message in log_entries:
    if level == "ERROR":
        print(f"[{date}] {level}: {message}")
# [2025-01-15] ERROR: Connection timeout

Summary

  • Basic unpacking: x, y = (1, 2)
  • Star unpacking: first, *rest = iterable
  • Swap variables: a, b = b, a
  • Loop unpacking: for x, y in pairs:
  • Ignore with _: name, _, email, _ = record
  • Nested unpacking: a, (b, c) = (1, (2, 3))
  • Function returns: name, age = get_user()

Next up: Tuple Methods →

Updated: