The Magic Behind Variable Swapping in Python

Posted by Afsal on 02-May-2025

Hi Pythonistas!

One of the many elegant features of Python is tuple unpacking — a powerful tool that makes your code more readable and Pythonic.

Let’s understand it using a popular example:

>>> a = 5
>>> b = 10
>>> a, b = b, a
>>> a
10
>>> b
5
>>> 

How did that work without a temporary variable?

What is Tuple Unpacking?
Tuple unpacking allows you to assign values from a tuple (or any iterable) directly to variables in a single, clean line.

>>> point = (3, 4)
>>> x, y = point
>>> x
3
>>> y
4
>>> 

Behind the scenes:

Python sees x, y = (3, 4). It "unpacks" the tuple and assigns x = 3, y = 4.

This works not just for tuples, but for lists, strings, and even custom iterables — as long as the number of items matches the number of variables.

The Magic Behind a, b = b, a
Let’s break it down:

Step 1: Right-Hand Side Packing
Python first evaluates the right-hand side before any assignment happens:

tmp = (b, a)
So if a = 5 and b = 10, this becomes:

tmp = (10, 5)

Step 2: Left-Hand Side Unpacking
Then Python unpacks tmp and assigns the values:

a, b = tmp  # a = 10, b = 5
This is all done in one atomic step — no intermediate variable required, and no chance of overwriting values prematurely.

✅ Why This Is Awesome

  • Clean, readable syntax
  • No temporary variable needed
  • Works with any iterable
  • Pythonic way to write swaps and multiple assignments

Tuple unpacking is one of those little Python features that feels like magic.