bhylu.com

Advertisements

Unpack Tuples

Unpacking gives positional values meaningful local names. A fixed record becomes easier to read when its fields have clear names.

Understand the idea

An ordinary unpack expects the same number of values as targets. A single starred target can collect the remainder into a list. Too few or too many input values raises ValueError, which helps expose a broken shape assumption instead of silently discarding data.

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

name, course, *tags = ("Mira", "Python", "evening", "online")
print(name, course)
print(tags)

Read the result

The tags value is ['evening', 'online'], while name and course hold the first two strings.

Try one change

Unpack a record with no tags and inspect the empty remainder.