← Python lessons

Python Tuple Unpacking: *rest, First and Last Values

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Sequence unpacking assigns items from an ordered sequence to names. A starred name collects extra items into a list.

Read Unpacking Values first. You should know list unpacking and why the number of names normally matches the number of values.

The goal is to unpack sequences whose length can vary, using one starred name. Each example runs on its own in the lesson editor; no imports or setup are needed.

Unpack a tuple or string

A tuple holds values in order, like a list, but its items cannot be replaced. You can write one with commas inside parentheses and unpack it like a list:

city, temperature = ("Hobart", 12)
print(city, temperature)

This prints Hobart 12. Unpacking also works on a string, one character per name:

first, second = "hi"
print(first)
print(second)

This prints h, then i. More generally, unpacking accepts an iterable: an object that supplies items one at a time. Use an ordered sequence when positions have meaning.

Collect the remaining values

Use ordinary unpacking when you need exactly one item per name. Use * before one name when the number of remaining items can vary:

first, *rest = (3, 5, 2)
print(first)
print(rest)

This prints 3, then [5, 2]. The starred name always receives a list, even when the source is a tuple or string. Without the star, first, rest = (3, 5, 2) raises ValueError because two ordinary names require exactly two items. With the star, rest collects all items left after first, rather than receiving just the second item.

Keep the first and last values

A starred name can go in the middle. Names before it receive the first items; names after it receive the last items:

first, *middle, last = [3, 5, 2, 6]
print(first, last)
print(middle)

This prints 3 6, then [5, 2]. Use this when the ends have fixed meanings but the number of items between them varies.

The starred part can be empty

Only the ordinary names require an item. The starred name can receive an empty list:

first, *middle, last = [3, 6]
print(first, last)
print(middle)

This prints 3 6, then []. Changing the source to [3] raises ValueError: there are still two ordinary names to fill. Try it to see the error.

Note: Only one name can have a star in the same unpacking pattern. Python cannot decide how to split the extra items between two starred names.

See also: Unpacking Values, Lists.

Your turn

Unpack record into name, a starred scores list, and status. Print each variable on its own line. Use the same pattern with empty_record, then print its scores to check the empty case.

record = ("Ada", 8, 6, 9, "ready")
empty_record = ("Bo", "waiting")
# unpack and print record's three parts, then unpack empty_record and print its scores

Expected output

Ada
[8, 6, 9]
ready
[]