Both asterisk unpacking (
*) and the walrus operator (:=) are powerful Python features used to write clean, concise and efficient code.Unpacking means assigning elements of an iterable (list, tuple, string, etc.) to multiple variables in a single statement.
# Basic unpacking
numbers = [10, 20, 30]
a, b, c = numbers
print(a) # 10
print(b) # 20
print(c) # 30
# Using * for extended unpacking: You can use * to capture multiple elements into a list when unpacking a collection
# Grabbing first, last, and everything in between
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # Output: 1
print(middle) # Output: [2, 3, 4] (always unpacks into a list)
print(last) # Output: 5
# Swapping variables
a = 10
b = 20
a, b = b, a
print(a, b) # 20 10**is called double-asterisk unpacking. It is mainly used to unpack dictionaries into keyword arguments or merge dictionaries.
# Merging dictionaries
a = {"name": "Ritesh"}
b = {"age": 21}
c = {**a, **b}
print(c) # {'name': 'Ritesh', 'age': 21}Operator | Purpose |
|---|---|
| Unpacks iterables into positional arguments |
| Unpacks dictionaries into keyword arguments |