bhylu.com

Advertisements

Assign Multiple Values

Python can unpack several values into several names. This is useful when a function or sequence returns a small record with a known shape.

Understand the idea

The number of target names normally needs to match the number of incoming values. A starred target can collect remaining items into a list. Unpacking communicates the expected structure, while repeated numeric indexing can hide what each position means. It still depends on the input having the documented order.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

city, seats = ("Nadiad", 12)
first, *remaining = [10, 20, 30]
print(city, seats)
print(first, remaining)

Read the result

The first line is Nadiad 12. The second shows 10 and [20, 30]. remaining is a new list containing the collected values.

Try one change

Unpack a name, an email, and a city from a tuple, then try input with one value missing and read the error.