Navigation

Python

How to Handle Multiple Assignment and Unpacking

Master Python tuple unpacking and multiple assignment for cleaner code. Swap variables, unpack functions, and handle iterables efficiently.

Table Of Contents

Problem

You need to assign multiple variables at once or unpack sequences like tuples and lists into separate variables.

Solution

# Basic multiple assignment
x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3

# Swap variables without temp variable
a, b = 10, 20
a, b = b, a
print(a, b)  # 20 10

# Unpack tuples and lists
coordinates = (5, 10)
x, y = coordinates
print(f"x: {x}, y: {y}")  # x: 5, y: 10

# Unpack function returns
def get_name_age():
    return "John", 25

name, age = get_name_age()
print(f"{name} is {age} years old")

# Use underscore for unwanted values
data = ("John", 25, "Engineer", "NYC")
name, age, _, city = data
print(f"{name}, {age}, {city}")  # John, 25, NYC

# Star operator for remaining items
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}")    # First: 1
print(f"Middle: {middle}")  # Middle: [2, 3, 4]
print(f"Last: {last}")      # Last: 5

# Unpack dictionaries
person = {"name": "Alice", "age": 30}
name, age = person.values()
print(f"{name}: {age}")  # Alice: 30

# Nested unpacking
nested = [(1, 2), (3, 4), (5, 6)]
for x, y in nested:
    print(f"x={x}, y={y}")

# Enumerate unpacking
items = ['a', 'b', 'c']
for index, value in enumerate(items):
    print(f"{index}: {value}")

Explanation

Multiple assignment uses tuple packing/unpacking internally. The star operator * collects remaining items into a list. Use underscores _ for values you don't need.

This syntax makes code more readable and eliminates the need for temporary variables when swapping or extracting values from sequences.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Python