How to Swap Variables in Python: Multiple Assignment Without Temporary Variables

In programming, there are times when you want to swap the values stored in two variables. For example, when implementing sorting algorithms.

目次

Traditional Method (Using a Temporary Variable)

In many programming languages, you need a third temporary variable (often called temp or tmp) to swap the values of two variables.

width = 800
height = 600

print(f"Before: Width={width}, Height={height}")

# 1. Save width value to temp variable
temp = width
# 2. Assign height value to width
width = height
# 3. Assign the saved temp (original width) value to height
height = temp

print(f"After:  Width={width}, Height={height}")

Output:

Before: Width=800, Height=600
After:  Width=600, Height=800

This method works reliably, but it requires three lines of code and an extra variable, making it slightly verbose.


The Pythonic Solution (Multiple Assignment)

Python provides a syntax to write this swap in a single line, intuitively, without using a temporary variable. This uses a feature called “Multiple Assignment” or “Tuple Unpacking”.

Syntax:

var1, var2 = var2, var1

Example: Here is how you write the swap for width and height in Python.

width = 800
height = 600

print(f"Before: Width={width}, Height={height}")

# Swap in one line using Python syntax
width, height = height, width

print(f"After:  Width={width}, Height={height}")

Output:

Before: Width=800, Height=600
After:  Width=600, Height=800

We achieved the exact same result as using the temp variable, but in just one line.

Why is this Possible?

The code width, height = height, width works internally as follows:

  1. First, the right side (height, width) is evaluated. At this point, a tuple (600, 800) is temporarily created in memory.
  2. Next, that tuple is unpacked and assigned to the variables width and height on the left side.
  3. As a result, width gets 600 and height gets 800 simultaneously.

Since the right side is evaluated before the assignment to the left side occurs, the values are not overwritten or lost, even without a temporary variable.


Swapping Three or More Variables

You can apply this syntax to swap three or more variables simultaneously (like a rotation).

a = 10
b = 20
c = 30
print(f"Before: a={a}, b={b}, c={c}")

# Rotate: a -> b, b -> c, c -> a
a, b, c = b, c, a

print(f"After:  a={a}, b={b}, c={c}")

Output:

Before: a=10, b=20, c=30
After:  a=20, b=30, c=10

Summary

  • In Python, while the traditional method using a temp variable works, it is not recommended.
  • By using the multiple assignment syntax a, b = b, a, you can write concise and efficient code in a single line.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次