Collections

Unpacking

Unpacking binds names from sequences and mappings concisely.

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 4
Left-side names bind to right-side positions; *rest gathers the middle into a list.

The 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] 4

describe(**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 Python

Notes

See also

Run the complete example

Example code

Expected output

3 4
1 [2, 3] 4
Ada Python

Execution time appears here after you run the example.