Assign Multiple Values
Tuple Unpacking
Python lets you assign multiple variables in one statement by unpacking values into them. This is commonly used when working with tuples or lists.
Example
# Basic unpacking
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# Swap variables without a temporary variable
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10
Output
1 2 3 20 10
Extended Unpacking
Python 3 supports extended unpacking with a star (*) expression, which captures multiple values. Underscore (_) is often used as a convention for ignored values.
Example
# Star expressions for remaining items
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# Ignoring values with _
_, important, _ = (9, 42, 13)
print(important) # 42
Output
1 [2, 3, 4] 5 42
Dictionary Unpacking
Dictionaries can be unpacked into function keyword arguments using **. The dictionary keys must exactly match the parameter names of the function.
Example
def connect(host, port, timeout):
print(f"Connecting to {host}:{port} with timeout {timeout}")
config = {'host': 'example.com', 'port': 8080, 'timeout': 30}
connect(**config)
Output
Connecting to example.com:8080 with timeout 30
ℹ️ Note: If a key does not match a parameter name, Python raises a TypeError.
Practical Applications
Multiple assignment is useful in many real-world scenarios, such as handling function returns, iterating through dictionaries, or unpacking configuration settings.
Example
# Processing CSV rows
for name, age, email in user_data:
send_email(email, f"Hello {name}, you're {age} years old")
Scenario | Example |
---|---|
Function returns | x, y = get_coordinates() |
Loop iteration | for key, value in dict.items() |
Config settings | host, port = load_config() |
Data processing | first, *rest = data_stream |