Concepts / Tuple Creation and Unpacking

Tuple Creation and Unpacking

The internal temporary tuple is handled automatically.

  • 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 Swap Problem

Swapping means exchanging the values held by two variables. This is useful when sorting numbers, exchanging player scores, or reordering data in a collection. In many programming languages, a temporary holding variable is needed so that the first value is not lost. Python provides a single-statement alternative: a, b = b, a.

python
Output
After the swap, a contains 20 and b contains 10.

Evaluation Before Assignment

The statement a, b = b, a works because Python evaluates the entire right side before assigning anything to the left side. With a equal to 10 and b equal to 20, Python first captures the current values on the right in this order: 20, then 10. It then assigns the first captured value to a and the second captured value to b. The original values are therefore preserved before either variable changes.

a1020right-side position 0a20b2010right-side position 1b10evaluateevaluateassignassign
How are the original values of a and b evaluated first and then assigned to the opposite variables without either value being lost?

A Complete Swap Trace

Worked example

Exchanging Two Scores

Start with score_a equal to 42 and score_b equal to 17. Exchange their values using tuple unpacking.

  1. 1
    Initial state

    score_a contains 42 and score_b contains 17.

  2. 2
    Evaluate the right side

    The right side score_b, score_a produces the values 17 and 42 in that order before either assignment occurs.

  3. 3
    Unpack to the left side

    The first captured value is assigned to score_a, and the second captured value is assigned to score_b.

Result

score_a contains 17 and score_b contains 42.

Code walkthrough
score_a = 42
score_b = 17
score_a, score_b = score_b, score_a
  1. 1
    The first line gives score_a the value 42.
  2. 2
    The second line gives score_b the value 17.
  3. 3
    The third line captures the current right-side values in the order score_b, score_a and assigns them to the left-side variables in the order score_a, score_b.
  • score_a starts with 42.
  • score_b starts with 17.
  • The right side is evaluated as 17, 42, then those values are assigned to score_a and score_b.
Output
score_a is 17 and score_b is 42.
score_a42score_a17score_b17score_b42swapswap
What do score_a and score_b contain before the swap, and what do they contain after executing the unpacking statement?

Why This Form Is Preferred

Tuple unpackingTemporary-variable method
a, b = b, atemp = a; a = b; b = temp
One statementSeveral assignment statements
No explicitly named temporary variableRequires a temporary holding variable
Concise, readable, and recognized as a swapLonger sequence that must preserve the first value manually
Python optimizes this common pattern and executes it more efficientlyTraditional approach is less efficient according to the source material

Both approaches exchange the values, but tuple unpacking is the more concise, readable, and efficient Python approach.

Tuple unpacking is not merely shorter syntax. The source describes this pattern as genuinely faster because Python's interpreter optimizes it as a common operation. It is also immediately recognizable to programmers as a swap, which improves readability.

Mistakes That Lose Values

  • Common mistake

    Assigning sequentially without a temporary value

    What it looks like
    a = b
    b = a
    Why it fails

    After the first assignment, a contains the original value of b. The original value of a is no longer available, so the second assignment gives b that same value instead of completing a swap.

    Do this instead

    Use a, b = b, a, or use a separately named temporary variable.

  • Common mistake

    Forgetting the comma syntax

    What it looks like
    a = b
    a = a
    Why it fails

    This is not a two-variable unpacking assignment. It performs separate assignments and does not exchange the values.

    Do this instead

    Write both target variables and both source values: a, b = b, a.

  • Common mistake

    Reversing the right-side order incorrectly

    What it looks like
    a, b = a, b
    Why it fails

    Each variable receives its own current value, so no swap occurs.

    Do this instead

    Place the source variables in the opposite order: a, b = b, a.

  • Common mistake

    Accidentally rotating more than two variables

    What it looks like
    a, b, c = b, c, a
    Why it fails

    This assigns values in a three-variable rotation rather than swapping only a and b.

    Do this instead

    For a two-variable swap, include only the two target variables and put their values in reversed order.

a, btwo targets=assignmentb, areversed sourcesa, bno exchangeb, c, athree-value rotationusesassigns from
What happens when the number of values and variables does not match, or when the right-side order is written incorrectly?

Practice the Pattern

EASY

Suppose first_item contains 3 and second_item contains 8. Write one Python statement that exchanges their values without creating a named temporary variable.

Hints
  • Put the two target variables on the left side.
  • Put the same variables in reverse order on the right side.
  • The pattern is target_a, target_b = source_b, source_a.

What do you think happens?

Before running the statement first_item, second_item = second_item, first_item, what values will the variables contain afterward?

  • first_item contains 3 and second_item contains 8

  • first_item contains 8 and second_item contains 3

  • Both variables contain 3

  • Both variables contain 8

Reveal answer
Answer:

first_item contains 8 and second_item contains 3.

Python evaluates the right side first, capturing second_item's value of 8 and first_item's value of 3. It then assigns those captured values to first_item and second_item in that order.

Key Takeaways

  1. 1
    The standard Python swap statement is a, b = b, a.
  2. 2
    Python evaluates the entire right side before assigning to the left side.
  3. 3
    The captured right-side values are then unpacked into the left-side variables, so neither original value is lost.
  4. 4
    Tuple unpacking is concise, readable, and faster than the traditional temporary-variable approach according to the source material.
  5. 5
    Sequential assignment without a temporary value, incorrect ordering, and accidental multi-variable rotations are common mistakes.

At a glance

  • Use a, b = b, a to exchange two variable values in one statement.
  • Python captures the right-side values before changing either left-side variable.
  • Tuple unpacking avoids an explicitly named temporary variable and is concise, readable, and efficient.
  • Do not replace the swap with sequential assignments such as a = b followed by b = a.
  • Check the order and number of values whenever unpacking does not produce the expected result.

Related concepts

More concepts starting with T