Unpacking Operators (*, **)
Overview
The unpacking operators (the single asterisk * for iterables and double asterisk ** for dictionaries) are syntactic magic. They 'explode' collections into individual components. Rather than writing loops to extract and merge items from lists or dictionaries, unpacking does it elegantly in a single operation. They are heavily used when merging configurations, cloning data, or passing dynamic arguments to functions.
Syntax
# Unpacking Iterables (Lists, Tuples, Sets)
list1 = [1, 2]
list2 = [3, 4]
merged_list = [*list1, *list2, 5]
print(merged_list) # [1, 2, 3, 4, 5]
# Catch-all unpacking assignments
first, *middle, last = [10, 20, 30, 40, 50]
print(first) # 10
print(middle) # [20, 30, 40]
print(last) # 50
# Unpacking Dictionaries
default_config = {"host": "localhost", "port": 80}
custom_config = {"port": 443, "debug": True}
# Merges both! Values on the right overwrite values on the left.
final_config = {**default_config, **custom_config}
print(final_config) # {'host': 'localhost', 'port': 443, 'debug': True}Common Pitfalls
Using a single
*on a dictionary. If you do[*my_dict], it unpacks the KEYS into a list, completely discarding the values. You must use**to unpack key-value pairs.Attempting to use multiple catch-all
*variables in a single assignment statement (e.g.,*a, *b, c = [1, 2, 3]). Python cannot determine where to draw the boundary, causing a SyntaxError.
Interview Questions
When unpacking two dictionaries into a new one ({**d1, **d2}), what happens to overlapping keys?
The dictionary unpacked last (on the far right) takes precedence. Its values will silently overwrite the values of any matching keys from dictionaries unpacked earlier.
Real-World Example
Passing a dictionary of parameters directly into a function as keyword arguments.
def create_user(username, email, role="guest"):
print(f"Created {role} {username} with email {email}")
user_data = {
"username": "admin_bob",
"email": "[email protected]",
"role": "admin"
}
# The ** operator explodes the dictionary into:
# create_user(username="admin_bob", email="[email protected]", role="admin")
create_user(**user_data)Check Your Knowledge
Test your understanding of Unpacking Operators (*, **) with these quick questions.