Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Swap Two Variables in Python

Trace two Python swaps side by side: a temporary variable and tuple unpacking. New programmers can see exactly when each original value is read and replaced.

BeginnerBasic Python ProgramsExample 3 of 25
swap-two-variables.py
1# Swapping using a temporary variable
2a = 5
3b = 10
4
5temp = a
6a = b
7b = temp
8
9print("After swapping (using temp): a =", a, "b =", b)
10
11# Swapping using Python tuple unpacking
12x = 5
13y = 10
14
15x, y = y, x
16
17print("After swapping (tuple unpacking): x =", x, "y =", y)

Sample Output

After swapping (tuple unpacking): x = 10 y = 5

The unpacking version finishes with x holding 10 and y holding 5.

In this one

  • Preserve a value before reassignment
  • Trace a three-assignment swap
  • Use simultaneous unpacking

How it works

  1. 1

    Store the old a in temp before changing a.

  2. 2

    Copy b into a, then temp into b, and print both.

  3. 3

    Initialize x and y, evaluate y and x, and unpack them into x and y.

Edge cases

Equal values

Start both variables at 5.

The swap still happens, but the displayed values look unchanged.

Only two sequential assignments

Write a = b followed by b = a.

The second assignment reads the new a, so the original a has already been lost.

What's going on

The temp version is what every language teaches: temp = a, a = b, b = temp. Save the old a before replacing it. Skip that save and both names can end up holding the old b.

For a = 5 and b = 10, temp keeps 5 while a becomes 10. The final assignment gives b that saved 5. Nothing about print does the swap; by then the work is finished.

Python also lets you write x, y = y, x. Conceptually the right-hand values are packed, then unpacked into the left-hand names. Both right-hand values are evaluated before either target changes. That ordering is the trick, not a hidden arithmetic formula. Use this version once you can trace the longer one.

After this program

If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why is temp needed in the first version?

Pick an answer to check it.

Question 2

When are the right-hand values in x, y = y, x read?

Pick an answer to check it.

Questions people ask

Why is temp needed in the first version?

It preserves the old a while a is replaced by b.

When are the right-hand values in x, y = y, x read?

Both are evaluated before the left-hand names receive their new values.

Does unpacking work with strings too?

Yes. Swapping names does not require their values to be numbers.