Concepts / Variable Swapping Using Tuple Assignment

Variable Swapping Using Tuple Assignment

Unpacking is a syntactic feature that assigns multiple variables from a sequence in one statement, equivalent to index-based assignment.

  • Programming

The One-Line Swap

Tuple assignment lets one statement assign values to multiple variables. The same unpacking pattern can swap two values: the value currently associated with a is assigned to b, while the value currently associated with b is assigned to a.

python
value 10value 20a10a20b20b10
How do the values move between a and b when a, b = b, a swaps them in one statement?

What do you think happens?

After these statements run, what values are associated with a and b? a, b = 10, 20 a, b = b, a

  • a is 10 and b is 20
  • a is 20 and b is 10
  • Both variables become 10
  • Both variables become 20
Reveal answer

Answer: a is 20 and b is 10

The second statement unpacks the two values in the order b, a into the targets a, b. The value from b goes to a, and the value from a goes to b.

Position Controls Assignment

Unpacking assigns sequence elements to variables by position. In x, y = sequence, the first element is assigned to x and the second element is assigned to y. The number of variables must exactly match the number of elements being unpacked.

values = (7, 12) x, y = values

position 1position 2Index 07x7Index 112y12
Which element at each index is assigned to each variable during unpacking?

Unpacking and Index Assignment

Unpacking is a syntactic feature that assigns multiple variables from a sequence in one statement. It is equivalent to assigning the values by their indexes.

Unpacking formIndex-based form
x, y = sequencex = sequence[0]; y = sequence[1]
first, second = valuesfirst = values[0]; second = values[1]
maps position 0maps position 1x, y = sequencepositional assignmentx = sequence[0]first elementy = sequence[1]second element
How does x, y = sequence correspond to assigning x = sequence[0] and y = sequence[1]?

Tuples Lists and Strings

Unpacking works uniformly with tuples, lists, strings, and any sequence type. The source sequence can differ, but the assignment rule remains positional: the first element goes to the first variable, the second element goes to the second variable, and so on.

python
Output
first is 3 and second is 4
left is 8 and right is 9
letter_one is h and letter_two is i
by positionby positionby positionTuple(3, 4)Variablesfirst, secondList[8, 9]Stringhi
How does unpacking assign values when the source is a tuple, list, or string?

Matching Element Counts

The number of target variables must exactly match the number of elements in the source sequence. If there are too many or too few targets, unpacking cannot complete and causes a ValueError.

count mismatchcount matchesa, b2 variablesa, b, c3 variables[1, 2, 3]3 elements[1, 2, 3]3 elements
What happens when there are more or fewer variables than elements in the sequence?
  • Using fewer variables than elements

    There are two target variables but three source elements.

    Fix: Use three variables, such as a, b, c = [1, 2, 3].

  • Using more variables than elements

    There are three target variables but only two source elements.

    Fix: Make the number of variables equal to the number of elements.

  • Assuming the source type changes the positional rule

    A string is still unpacked by position, just like a tuple or list.

    Fix: Count the string's sequence elements and match them with the target variables.

A Reliable Unpacking Check

  1. Identify the source sequence.
  2. Count its elements.
  3. Count the target variables.
  4. Match the first source element with the first target, the second with the second, and so on.
  5. If the counts differ, add or remove target variables before running the assignment.
  6. For a swap, place the variables in the opposite order on the right side.

Tracing a Three-Element Unpack

Determine the values assigned by first, second, third = [4, 5, 6].

Count the source elements: The list contains three elements: 4, 5, and 6.

Count the targets: There are three target variables: first, second, and third.

Map positions: The first element 4 goes to first, 5 goes to second, and 6 goes to third.

first is 4, second is 5, and third is 6.

Practice the Mapping

MEDIUM

For each statement, identify the value assigned to every variable. Then decide whether any statement causes a ValueError. 1. left, right = (2, 9) 2. first, second, third = ["a", "b", "c"] 3. one, two = "cat" 4. score, best = 40, 75 5. score, best = best, score

Hints
  • Map elements from left to right.
  • Check that the number of variables equals the number of sequence elements.
  • For the final statement, read the right side in the order best, score.
Output
1. left is 2 and right is 9.
2. first is a, second is b, and third is c.
3. The statement causes a ValueError because the string provides three elements and there are only two variables.
4. score is 40 and best is 75.
5. score becomes 75 and best becomes 40.

Key Takeaways

  1. Unpacking assigns multiple variables from one sequence in a single statement.
  2. Assignment follows position: the first element goes to the first variable, the second element goes to the second variable, and so on.
  3. Unpacking is equivalent to index-based assignment such as x = sequence[0] and y = sequence[1].
  4. Tuples, lists, strings, and other sequence types can be unpacked using the same positional rule.
  5. The number of variables must exactly match the number of elements, or a ValueError occurs.
  6. Writing the variables in reverse order on the right side provides a concise way to swap their values.

Key Takeaways

  • Unpacking maps sequence elements to multiple variables by position.
  • Tuple assignment can swap two variable values in one statement.
  • The same unpacking approach works with tuples, lists, and strings.
  • Unpacking corresponds to index-based assignment.
  • A mismatch between target variables and source elements causes a ValueError.