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
Interactive lab

Try it: Tuples: Comparison and Unpacking

How Python compares tuples lexicographically — the first unequal pair of items decides, a shorter prefix is smaller, int vs str ordering raises TypeError — and how tuple assignment unpacks and swaps values.

How it works

  1. Walk both tuples from index 0 while the items are equal.
  2. At the first difference, that pair alone decides (later items are never looked at); strs compare by code point.
  3. If one tuple runs out first, the shorter one is smaller; ordering an int against a str raises TypeError.
  4. Unpacking checks the count first: too many or too few values raise ValueError before any name is bound.
  5. a, b = b, a builds the right-hand tuple from the old values, then unpacks it into the names.

Default run (4 steps): Evaluate (1, 'pear', 7) < (1, 'plum', 2): compare item by item from index 0. … 'pear' < 'plum' is True (strings compare by code point: 'e' is 101, 'l' is 108), so (1, 'pear', 7) < (1, 'plum', 2) is True.

Simplified: Flat tuples of up to 6 ints or short ASCII strs (no nested tuples, floats or starred targets).

Educational simulation

Loading the simulation…

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
a10a20b20b10value 10value 20
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, 20a, 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.

Code walkthrough
values = (7, 12)
x, y = values
  1. 1
    The sequence has the elements 7 and 12.
  2. 2
    The target list has x and y.
  3. 3
    The first position maps 7 to x.
  4. 4
    The second position maps 12 to y.
  • values contains two sequence elements.
  • x is the first target, so it receives the first element.
  • y is the second target, so it receives the second element.
Output
x is 7 and y is 12
Index 07x7Index 112y12position 1position 2
Which element at each index is assigned to each variable during unpacking?

Unpacking and Index Assignment

Definition

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]

The two forms express the same positional mapping described by the source material.

x, y = sequencepositional assignmentx = sequence[0]first elementy = sequence[1]second elementmaps position 0maps position 1
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
Tuple(3, 4)Variablesfirst, secondList[8, 9]Stringhiby positionby positionby position
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.

Before
a, b = [1, 2, 3]

Two variables receive three elements, so unpacking fails.

After
a, b, c = [1, 2, 3]

Three variables receive three elements, so the counts match.

a, b2 variablesa, b, c3 variables[1, 2, 3]3 elements[1, 2, 3]3 elementscount mismatchcount matches
What happens when there are more or fewer variables than elements in the sequence?
  • Common mistake

    Using fewer variables than elements

    What it looks like
    a, b = [1, 2, 3]
    Why it fails

    There are two target variables but three source elements.

    Do this instead

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

  • Common mistake

    Using more variables than elements

    What it looks like
    a, b, c = [1, 2]
    Why it fails

    There are three target variables but only two source elements.

    Do this instead

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

  • Common mistake

    Assuming the source type changes the positional rule

    What it looks like
    first, second = "hi"
    Why it fails

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

    Do this instead

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

A Reliable Unpacking Check

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

Tracing a Three-Element Unpack

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

  1. 1
    Count the source elements

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

  2. 2
    Count the targets

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

  3. 3
    Map positions

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

Result

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

At a glance

  • 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.

Related concepts

More concepts starting with V