Course contentsShow
← Python
Lesson 233 of 1,0604. Data Structures MasteryFree lesson

Unpacking Iterables with Extended Assignment

You will use the starred expression operator to capture arbitrary numbers of elements from iterables into dynamic variables during sequence unpacking.

Unpacking Iterables with Extended Assignment

In this lesson, you will learn how to capture multiple elements from an iterable into a single variable using the starred expression operator (*).

Mastering the Starred Expression

Previously, you learned how to unpack sequences by assigning individual variables to each element, like a, b = (1, 2). However, this approach fails if your iterable has more elements than you have variables. Extended assignment solves this by allowing you to designate one variable as a "catch-all" collector.

When you place an asterisk (*) before a variable name during unpacking, Python assigns that variable a list containing all the remaining elements that weren't captured by the other variables.

Consider this example:

data = [10, 20, 30, 40, 50]

# Unpack the first, the last, and everything in between
first, *middle, last = data

print(first)   # Output: 10
print(middle)  # Output: [20, 30, 40]
print(last)    # Output: 50

How it Works

When Python sees the *middle, it performs a calculation: it allocates the specific variables you requested first (first and last), then gathers everything else into a list and assigns it to middle.

This is incredibly flexible. You can even use it at the beginning or the end:

# Capture everything except the first two items
a, b, *rest = [1, 2, 3, 4, 5]
# a=1, b=2, rest=[3, 4, 5]

# Capture everything except the last item
*beginning, end = [1, 2, 3, 4, 5]
# beginning=[1, 2, 3, 4], end=5

If there are no elements left over for the starred variable, Python will simply assign an empty list ([]) to it, preventing an error. Just remember that you can only use one starred expression per assignment; Python needs to know exactly which variable is the "catch-all" bucket. This technique makes your code much cleaner than manually slicing lists when you only care about specific parts of a sequence.

Key Takeaway: Use the starred expression (*variable) to dynamically capture an arbitrary number of remaining elements into a list during sequence unpacking.