Collections
Unpacking
Tuple unpacking assigns each position to a name in one statement: x receives the first element of point and y the second. The assignment fails loudly if the number of names and elements disagree, which catches shape mistakes early.
Source
point = (3, 4)
x, y = point
print(x, y)Output
3 4The starred name collects however many elements the head and tail don't claim — here first and last take the ends and *middle gathers the rest into a list. The same list works whether it has four elements or forty.
Source
first, *middle, last = [1, 2, 3, 4]
print(first, middle, last)Output
1 [2, 3] 4describe(**data) spreads the dictionary's keys as keyword arguments, so the call site never repeats name= and language= by hand. This is the bridge between dict-shaped data (configuration, parsed JSON) and function signatures.
Source
def describe(name, language):
print(name, language)
data = {"name": "Ada", "language": "Python"}
describe(**data)Output
Ada PythonNotes
- Starred unpacking collects the remaining values into a list.
- Dictionary unpacking with ** is common when calling functions with structured data.
- Prefer indexing when you need one position; prefer unpacking when naming several positions makes the shape clearer.
See also
- related: Tuples
- next depth: Multiple Return Values
- next depth: Args and Kwargs
- related: Dictionaries
Run the complete example
Expected output
3 4
1 [2, 3] 4
Ada Python
Execution time appears here after you run the example.