Concepts / Iterables and Iteration

Iterables and Iteration

Tuple assignment unpacks multiple values from a tuple into separate variables in a single statement, with the number of variables and values required to match exactly.

  • Programming

A Tuple with Two Destinations

Tuple assignment lets one statement unpack multiple values from a tuple into separate variables. The central rule is positional: the first value goes to the first variable, the second value goes to the second variable, and so on. For unpacking to succeed, the number of variables and values must match exactly.

python

What do you think happens?

After the assignment, which value is bound to each variable?

  • x contains 'have' and y contains 'fun'
  • x contains 'fun' and y contains 'have'
  • Both variables contain the complete tuple
Reveal answer

Answer: x contains 'have' and y contains 'fun'

Python matches positions. The value at tuple position 0, 'have', is assigned to x, and the value at position 1, 'fun', is assigned to y.

Position-by-Position Unpacking

In the statement x, y = m, the left side provides two variable destinations and the right side provides the two values from m. Python pairs them by position. The first tuple element is assigned to x, while the second tuple element is assigned to y. Both bindings occur together as one assignment operation rather than as two separately written assignments.

containscontainsposition 0position 1mtuple'have'position 0x'have''fun'position 1y'fun'
How does each value in a tuple move into the variable at the corresponding position?

Read tuple assignment from right to left as a positional transfer: values are produced on the right, then matched with destinations on the left. The ordering on both sides matters.

Swapping Without a Temporary Variable

Tuple assignment is especially useful for swapping two variables. The Pythonic idiom is a, b = b, a. It exchanges the values without requiring a separately named temporary variable.

python

What do you think happens?

After a, b = b, a executes, what values do a and b contain?

  • a contains 'first' and b contains 'second'
  • a contains 'second' and b contains 'first'
  • Both variables contain 'first'
Reveal answer

Answer: a contains 'second' and b contains 'first'

Python evaluates the complete right side first. It obtains the current value of b followed by the current value of a, then assigns those two values to a and b in that order.

after assignmentafter assignmenta'first'a'second'b'second'b'first'
How do the values of two variables change before and after a tuple-assignment swap?

The Right Side Runs First

The swap is safe because Python evaluates the entire right-hand side before binding anything on the left. In a, b = b, a, Python first obtains the old value of b and the old value of a in that order. It then unpacks those values into a and b. Because the right side is completed before the left side changes, one original value cannot be overwritten before it is used.

evaluate firstunpackstore a valuecomplete swapa, b = b, aright side valuesold b, old aswapped a and btemporary-variableswaptemporary variableswapped a and b
What steps and temporary storage differ between tuple assignment and traditional temporary-variable swapping?

Prefer tuple assignment for a two-variable swap. The source describes it as more readable, faster, and more idiomatic than traditional approaches that use a temporary variable.

When Counts Do Not Match

Unpacking requires an exact count match. If three values are supplied but only two variables are available, Python has nowhere to assign the third value and raises a ValueError. The same principle applies whenever the number of variables and values differs.

python
Output
ValueError: too many values to unpack
unpackdoes not match1, 2, 3three valuesValueErrorcount mismatcha, btwo variables
What happens when the number of variables does not match the number of values being unpacked?
  • Providing more values than variables

    There are three values but only two destinations, so the third value has no variable to receive it.

    Fix: Make the number of variables match the number of values before running the assignment.

  • Providing fewer values than variables

    The exact-count rule is not satisfied; one variable would have no corresponding value.

    Fix: Check both sides of the assignment and ensure their counts are equal.

Practice the Binding Order

EASY

Suppose a tuple contains the values 10 and 20. Write a tuple-assignment statement that places 10 in first_value and 20 in second_value. Then write a second statement that swaps the values of those two variables using tuple assignment.

Hints
  • Place the variable names on the left and the tuple values on the right.
  • For the swap, put the variables in reverse order on the right side.
  • Check that both assignments have the same number of destinations and values.

Diagnosing an Unpacking Error

An assignment has two variables on the left and three values on the right. Explain why it raises ValueError and describe the required correction.

Count the destinations: The left side provides two variables.

Count the values: The right side provides three values.

Compare the counts: The counts differ, so the assignment cannot give every value a destination.

Change the assignment so that the number of variables exactly matches the number of values.

Key Takeaways

  1. Tuple assignment unpacks values by position into separate variables.
  2. The number of variables must exactly match the number of values being unpacked.
  3. The idiom a, b = b, a swaps two values without a separately named temporary variable.
  4. Python evaluates the complete right-hand side before binding the left-hand variables.
  5. A mismatched unpacking count raises ValueError and should be debugged by counting both sides.

Key Takeaways

  • Tuple assignment maps values to variables according to their positions.
  • Successful unpacking requires equal counts on both sides.
  • Tuple assignment makes variable swapping concise and avoids a named temporary variable.
  • Python evaluates the right side first, protecting the original values during a swap.
  • ValueError during unpacking usually indicates a mismatch between the number of variables and values.