25. Python Unpacking Iterables

In Python, unpacking allows you to assign elements from an iterable (such as a tuple, list, or string) directly into individual variables in a single line of code.
Instead of accessing elements individually by their index numbers, unpacking provides a clean and readable way to extract values.
Unpacking works with any sequence or collection where Python can iterate through elements step-by-step.
# Traditional indexing
point = (10, 20)
x = point[0]
y = point[1]

# Unpacking into variables
x, y = point  # x gets 10, y gets 20

25.1. Basic Tuple and List Unpacking

Basic unpacking works by placing variables on the left side of an assignment operator and an iterable on the right:

  • Exact Matching: The number of variables on the left must match the exact number of elements in the iterable on the right.

  • Order Matters: Elements are assigned sequentially from left to right based on their position in the collection.

  • Supported Iterables: Unpacking works on tuples, lists, sets, ranges, and strings.

  • ValueError on Mismatch: Providing too few or too many variables compared to the iterable elements will raise a ValueError.

# Unpacking a tuple
coordinates = (4, 9, 2)
x, y, z = coordinates

# Unpacking a list
colors = ["red", "green", "blue"]
primary, secondary, tertiary = colors

# Unpacking a string
a, b, c = "CAT"  # a="C", b="A", c="T"

25.1.1. Quiz: Basic Tuple and List Unpacking

25.1.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
ValueError
a
match
order
variables

1. Unpacking assigns elements from an iterable into multiple Drop here in a single line.
2. The number of variables on the left must Drop here the number of items in the iterable.
3. If variable count does not match the element count, Python raises a Drop here.
4. Unpacking assigns values based on their sequential Drop here in the iterable.
5. Unpacking the string `"PY"` into `a, b` assigns `"P"` to Drop here.

25.1.1.2. Code Ordering Examples

Example 1: Unpack a 2D coordinate tuple into x and y variables and print them.

Drag and drop lines into the correct order and click to adjust indentation:
☰
x, y = point
☰
print("X:", x)
☰
print("Y:", y)
☰
point = (5, 12)

Example 2: Unpack a list of three fruit names into individual variables.

Drag and drop lines into the correct order and click to adjust indentation:
☰
f1, f2, f3 = fruits
☰
print(f1, f2, f3)
☰
fruits = ["apple", "banana", "cherry"]

Example 3: Swap two variable values in a single line using unpacking logic.

Drag and drop lines into the correct order and click to adjust indentation:
☰
a, b = b, a
☰
b = 20
☰
print(a, b)
☰
a = 10

25.1.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What happens if you run a, b = [10, 20, 30] in Python?

Correct! The list has 3 items, but only 2 variables are provided.

Incorrect. Python requires exact matching unless star unpacking is used.

Incorrect. Standard unpacking does not collect remaining elements without *.

Incorrect. Variable names must be explicitly declared.

What is stored in variable y after executing x, y, z = (1, 2, 3)?

Correct! Positional unpacking assigns the second element (2) to the second variable (y).

Incorrect. 1 is assigned to x.

Incorrect. 3 is assigned to z.

Incorrect. Unpacking assigns individual elements, not the entire tuple.

Given char1, char2 = "GO", what value does char2 hold?

Correct! Strings are iterables; unpacking assigns character “G” to char1 and “O” to char2.

Incorrect. “G” is assigned to char1.

Incorrect. Characters are unpacked individually.

Incorrect. 2 characters match 2 variables perfectly.

How does Python perform variable swapping using a, b = b, a?

Correct! The right side evaluates to a tuple (b, a) before unpacking into a, b.

Incorrect. Python constructs a tuple under the hood to perform the swap safely.

Incorrect. Unpacking eliminates the need for manual temp variables.

Incorrect. Tuple unpacking swaps any data type.

What error occurs when running x, y, z = (1, 2)?

Correct! 3 variables need 3 elements, but only 2 are provided.

Incorrect. Missing elements trigger ValueError.

Incorrect. IndexErrors occur during manual indexing, not tuple unpacking.

Incorrect. All variable positions are syntactically valid.

Which statement correctly unpacks a 3-element list data = [100, 200, 300]?

Correct! Matches 3 variables to 3 list elements.

Incorrect. Mismatched count causes ValueError.

Incorrect. == tests equality rather than assigning unpacking targets.

Incorrect. This assigns undefined variables to data.

Given first, second = range(2), what is the value of second?

Correct! range(2) generates values 0 and 1; first gets 0, second gets 1.

Incorrect. 0 is assigned to first.

Incorrect. range(2) excludes 2 (generates 0, 1).

Incorrect. Values are unpacked individually.

Why is unpacking preferred over indexing (e.g., x = item[0])?

Correct! Unpacking improves readability and reduces boilerplate code.

Incorrect. It enhances code quality without drastic performance differences.

Incorrect. Indexing remains standard for accessing specific elements.

Incorrect. Unpacked variables remain mutable.

Given a, b, c = [1, 1, 1], what is the value of a + b + c?

Correct! Each variable gets 1; $1 + 1 + 1 = 3$.

Incorrect. Three distinct variables each hold value 1.

Incorrect. Unpacked values are numbers, not a list.

Incorrect. Adding integers is valid.

What happens when you unpack a set like a, b = {10, 20}?

Correct! Sets are unordered, so variable assignment order may vary.

Incorrect. Sets are iterables and support unpacking.

Incorrect. Sets do not auto-sort during unpacking.

Incorrect. Data types of elements remain unchanged.

Question 1 of 0

25.2. Extended Unpacking (The Asterisk * Operator)

When the number of elements in an iterable does not match the number of variables, Python provides the asterisk (``*``) operator for extended unpacking:

  • Catch-All Variable: Placing * before a variable name gathers remaining elements into a list.

  • Flexible Position: The starred variable can be at the beginning, middle, or end of the variable sequence.

  • Single Asterisk Limit: You can only use one starred variable per unpacking expression.

  • Empty List Output: If there are no extra elements left to capture, the starred variable receives an empty list [].

numbers = [1, 2, 3, 4, 5]

# Star at the end
first, *rest = numbers  # first = 1, rest = [2, 3, 4, 5]

# Star in the middle
first, *middle, last = numbers  # first = 1, middle = [2, 3, 4], last = 5

# Star at the start
*head, last = numbers  # head = [1, 2, 3, 4], last = 5

25.2.1. Quiz: Extended Unpacking

25.2.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
*
1
[]
empty
list

1. The Drop here operator is used in extended unpacking to collect multiple remaining elements.
2. A starred variable always stores collected elements inside a Drop here.
3. You can use a maximum of Drop here starred variable in a single unpacking assignment.
4. If there are no spare elements left for a starred variable, it receives an Drop here list.
5. In `first, *others = [10]`, the variable `others` evaluates to Drop here.

25.2.1.2. Code Ordering Examples

Example 1: Separate the first item of a list from the remaining items using extended unpacking.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print("Top score:", top)
☰
scores = [95, 88, 72, 60]
☰
print("Others:", others)
☰
top, *others = scores

Example 2: Extract the head, middle, and tail of a sequence.

Drag and drop lines into the correct order and click to adjust indentation:
☰
first, *middle, last = items
☰
print(first, middle, last)
☰
items = ["A", "B", "C", "D", "E"]

Example 3: Capture all leading items into a list and isolate the final item.

Drag and drop lines into the correct order and click to adjust indentation:
☰
*previous, current = data
☰
print("Current:", current)
☰
data = [1, 2, 3, 4]
☰
print("History:", previous)

25.2.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Given a, *b, c = [1, 2, 3, 4, 5], what is the value of b?

Correct! a gets 1, c gets 5, and starred variable b collects the middle elements into a list.

Incorrect. Extended unpacking always produces a list, not a tuple.

Incorrect. Starred variables gather all unassigned middle elements.

Incorrect. c absorbs the final element 5.

What data type does a starred variable (e.g. *rest) produce?

Correct! Extended unpacking always packs remaining elements into a list.

Incorrect. Extended unpacking explicitly produces lists.

Incorrect. Results are stored in ordered lists.

Incorrect. Extended unpacking evaluates and gathers items into concrete lists.

What is the value of extra in a, b, *extra = [10, 20]?

Correct! All elements are absorbed by a and b, leaving an empty list for extra.

Incorrect. Starred variables receive empty lists [] rather than None.

Incorrect. Extended unpacking handles zero surplus elements gracefully.

Incorrect. Output is an empty list container [].

What happens if you attempt to run *a, *b = [1, 2, 3, 4]?

Correct! Multiple starred target variables in one assignment are forbidden due to ambiguity.

Incorrect. Python cannot determine where to split items between two starred variables.

Incorrect. Syntax prevents multiple starred variables.

Incorrect. SyntaxError occurs during parsing.

Given *start, end = "PYTHON", what does end hold?

Correct! end absorbs the final character “N”, while start collects [‘P’, ‘Y’, ‘T’, ‘H’, ‘O’].

Incorrect. end absorbs only the last element.

Incorrect. That list is stored in start.

Incorrect. start absorbs leading elements.

What does first, *rest = (5, 10, 15) assign to rest?

Correct! Unpacking converts tuple remnants into a list [10, 15].

Incorrect. Starred unpacking always outputs a list type regardless of source iterable.

Incorrect. rest captures all remaining elements.

Incorrect. rest captures a list containing both 10 and 15.

Given a, *b, c, d = [1, 2, 3], what is the value of b?

Correct! a=1, c=2, d=3; leaving 0 surplus elements for starred variable b, resulting in [].

Incorrect. c and d absorb 2 and 3 sequentially.

Incorrect. 3 items fit into 3 positional requirements, giving b an empty list.

Incorrect. b receives an empty list [].

What is output by x, *y = range(4); print(y)?

Correct! range(4) provides 0, 1, 2, 3. x gets 0, y receives remaining list [1, 2, 3].

Incorrect. x absorbs 0.

Incorrect. Starred variables output lists.

Incorrect. y captures all remaining items into a list.

Why does Python disallow *a, b, *c = [1, 2, 3]?

Correct! Python cannot determine how many elements belong to each starred list.

Incorrect. Starred variables can exist at the beginning or end.

Incorrect. Single starred middle variables are valid.

Incorrect. Extended unpacking is valid in assignments.

Given head, *tail = "A", what is the value of tail?

Correct! head gets “A”, leaving no remaining characters, so tail gets [].

Incorrect. “A” is assigned to head.

Incorrect. Extended unpacking creates a list [], not an empty string.

Incorrect. Valid extended unpacking assignment.

Question 1 of 0

25.3. Unpacking in Loops and Functions

Unpacking is frequently used inside for loops and function calls to streamline data handling:

  • Loop Unpacking: Automatically unpack nested structures (like tuples inside a list) directly in the loop header.

  • Dictionary Iteration: Use .items() with unpacking to access keys and values simultaneously.

  • Argument Unpacking (*args): Use * in function calls to expand list or tuple elements into positional arguments.

  • Keyword Unpacking (**kwargs): Use ** in function calls to unpack dictionary key-value pairs into keyword arguments.

# Unpacking in a for loop
pairs = [(1, "one"), (2, "two"), (3, "three")]
for num, word in pairs:
    print(num, "->", word)

# Function argument unpacking (* operator)
def calculate_sum(a, b, c):
    return a + b + c

nums = [5, 10, 15]
result = calculate_sum(*nums)  # Equivalent to calculate_sum(5, 10, 15)

25.3.1. Quiz: Unpacking in Loops and Functions

25.3.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
*
**
2
iteration
key

1. When looping over dictionary items with `.items()`, unpacking extracts Drop here and value pairs.
2. The Drop here operator unpacks list or tuple elements as individual positional function arguments.
3. The Drop here operator unpacks dictionary key-value pairs as keyword function arguments.
4. Unpacking inside a `for` loop header automatically extracts elements for each Drop here.
5. In `for x, y in [(1, 2)]`, the variable `y` receives Drop here.

25.3.1.2. Code Ordering Examples

Example 1: Iterate over a list of coordinate tuples using loop unpacking.

Drag and drop lines into the correct order and click to adjust indentation:
☰
points = [(0, 0), (3, 4), (5, 12)]
☰
print("X:", x, "Y:", y)
☰
for x, y in points:

Example 2: Unpack dictionary keys and values simultaneously in a loop.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(name, "received grade", grade)
☰
for name, grade in student_grades.items():
☰
student_grades = {"Alice": "A", "Bob": "B"}

Example 3: Unpack a list of numbers into a function requiring three parameters.

Drag and drop lines into the correct order and click to adjust indentation:
☰
return a + b + c
☰
 
☰
print(total)
☰
values = [10, 20, 30]
☰
def add_three(a, b, c):
☰
total = add_three(*values)

25.3.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What does for k, v in my_dict.items(): do in Python?

Correct! .items() yields (key, value) tuples that unpack cleanly in loop headers.

Incorrect. k, v performs variable assignment unpacking.

Incorrect. Both keys and values are processed.

Incorrect. Unpacking iterates through existing items.

Given def add(a, b): return a + b and nums = [3, 7], how do you pass nums into add using unpacking?

Correct! * unpacks list elements into positional parameters a and b.

Incorrect. Passing nums directly sends 1 list argument instead of 2 positional numbers.

Incorrect. ** unpacks dictionary mappings, not lists.

Incorrect. Asterisk precedes variable name.

What is output by data = [(1, 2), (3, 4)]; print([x + y for x, y in data])?

Correct! First iteration $1 + 2 = 3$; second iteration $3 + 4 = 7$.

Incorrect. Loop unpacks pairs and evaluates x + y sums.

Incorrect. List comprehension outputs calculated results.

Incorrect. List comprehension returns a list of individual tuple sums.

Which operator unpacks a dictionary into keyword arguments inside a function call?

Correct! Double asterisk ** unpacks dictionary key-value pairs into keyword arguments.

Incorrect. Single asterisk * unpacks positional iterables like lists/tuples.

Incorrect. & is bitwise AND operator.

Incorrect. % is modulus operator.

Given def greet(name, age): print(f"{name} is {age}") and info = {"name": "Sam", "age": 14}, which call is correct?

Correct! ** unpacks key-value dictionary pairs into name=”Sam”, age=14 keyword arguments.

Incorrect. Single * unpacks only dictionary keys (“name”, “age”) positionally.

Incorrect. Passes 1 dictionary argument to function expecting 2 parameters.

Incorrect. Invalid operator syntax.

What occurs when calling add(*[1, 2, 3]) on a function def add(x, y):?

Correct! Unpacking 3 elements supplies 3 arguments to a 2-parameter function.

Incorrect. Mismatched argument counts raise TypeError.

Incorrect. Exact parameter counts are enforced.

Incorrect. Argument count exceeds parameter definition.

In for i, (a, b) in enumerate([(10, 20), (30, 40)]):, what is assigned to a on the second iteration?

Correct! Second tuple is (30, 40); (a, b) unpacks a=30 and b=40.

Incorrect. 1 is the enumerate index i on second iteration.

Incorrect. 10 belongs to first tuple on first iteration.

Incorrect. 40 is assigned to b.

What is the primary benefit of unpacking inside loop headers?

Correct! Directly names tuple elements in the loop signature.

Incorrect. Improves syntax readability rather than loop execution speed.

Incorrect. Iteration order matches original collection sequence.

Incorrect. Loop direction remains unchanged.

What happens when unpacking dictionary keys in a, b = {"x": 1, "y": 2}?

Correct! Iterating over a dictionary directly yields its keys.

Incorrect. Accessing values requires .values() or dictionary lookup.

Incorrect. Key-value tuples require .items().

Incorrect. Unpacking dictionaries directly unpacks key sequences.

Given nums = [1, 2, 3], what does print(*nums) execute as?

Correct! Unpacking expands list elements into separate positional arguments passed to print.

Incorrect. Unpacking strips list enclosing brackets.

Incorrect. print displays space-separated arguments rather than summing them.

Incorrect. Elements are printed as separate positional arguments.

Question 1 of 0