Published on

Understanding `Variable-length unpacking` in Python

Authors
  • avatar
    Name
    hwahyeon
    Twitter

Variable-length unpacking is an extended feature of tuple unpacking that allows you to handle a fixed number of values and the remaining values in a sequence simultaneously.

Variable-length unpacking example

numbers = [1, 2, 3, 4, 5]
first, second, *rest = numbers
print(first)   # 1
print(second)  # 2
print(rest)    # [3, 4, 5]

As shown above, the remaining values 3, 4, 5 are captured by *rest.

1. Creating the list on the right-hand side:

Python first creates the list numbers = [1, 2, 3, 4, 5] in memory.

2. Unpacking process:

first is assigned numbers[0], which is 1. second is assigned numbers[1], which is 2. When Python encounters the *rest, it creates a new list [3, 4, 5] in memory. Then, the rest variable is linked to this new list.

More examples

  • * can only be used with one variable at a time Using * on more than one variable will result in a SyntaxError.
numbers = [1, 2, 3, 4, 5]
first, *middle, *rest = numbers  # SyntaxError 발생
  • * can be used in different positions: You can place the * operator at any position in the unpacking.
first, *middle, last = [1, 2, 3, 4, 5]
print(first)      # 1
print(middle)     # [2, 3, 4]
print(last)       # 5

1. List Creation and First Element Assignment

Python creates the list [1, 2, 3, 4, 5] in a specific memory location and holds a reference to it. The first element of the list, 1, is retrieved from memory and copied into the variable first, which now references the number 1.

2. Unpacking Middle and Last Elements

Since *middle is marked with the *, Python interprets this as needing to capture all remaining values between first and last. The values [2, 3, 4] are assigned to middle. Finally, the last value, 5, is assigned to the variable last.

3. Garbage Collection of the Original List

After this code executes, the original list [1, 2, 3, 4, 5] is no longer directly referenced. Python's garbage collector (GC) will eventually remove this list from memory once all references to it are gone.