Scrollable Nav Bar

Python program that swaps the values of two variables

This article explains several simple and idiomatic ways to write a Python program that swaps the values of two variables. Each method includes code, a short explanation, and notes so you can choose the best approach for your situation.


Task

Given two variables a and b, exchange their values so that after the operation a holds the original value of b and b holds the original value of a.

Example:

# before
a = 5
b = 10

# after swap
# a == 10, b == 5
Code language: PHP (php)

Using a temporary variable

This is a clear, language-agnostic method that works everywhere.

# Using a temporary variable
a = 5
b = 10

print("Before swap:", a, b)

temp = a
a = b
b = temp

print("After swap:", a, b)
Code language: PHP (php)

Output:

Explanation:

  1. Save a into temp so its value is not lost.
  2. Assign b to a.
  3. Restore the saved value from temp into b.

Pythonic tuple unpacking

Python supports multiple assignment (tuple unpacking), which makes swapping concise and readable.

# Tuple unpacking
a = 5
b = 10

print("Before swap:", a, b)

a, b = b, a

print("After swap:", a, b)
Code language: PHP (php)

Output :

Explanation:
The right-hand side (b, a) creates a temporary tuple of values and Python unpacks it into a and b. This performs the swap in one readable statement.


Using arithmetic

You can swap numeric values using arithmetic operations. This avoids an extra variable but is less readable and has caveats.

# Using addition and subtraction
a = 5
b = 10

print("Before swap:", a, b)

# Correct in-place arithmetic swap
a = a + b
b = a - b
a = a - b

print("After swap:", a, b)
Code language: PHP (php)

Important caveats:

  • Works only for numeric types (ints, floats) and can overflow for very large integers if implemented in languages with fixed-width integers (Python has arbitrary-precision integers so overflow is not a problem here).
  • Less readable and more error-prone than tuple unpacking.

Using XOR bitwise trick

Another classic trick uses bitwise XOR. It works only for integers and is rarely used in Python because tuple unpacking is clearer.

# XOR swap — integer-only
a = 5
b = 10

print("Before swap:", a, b)

a = a ^ b
b = a ^ b
a = a ^ b

print("After swap:", a, b)
Code language: PHP (php)

Caveats:

  • Only works with integers.
  • Readability suffers; rarely used in modern Python.

Using a function

You can wrap swapping logic in a function; this is useful for clarity when reusing the pattern.

def swap(x, y):
    return y, x

# usage
a, b = 1, 2
print("Before:", a, b)
a, b = swap(a, b)
print("After:", a, b)
Code language: PHP (php)

This uses tuple returns and unpacking under the hood.


Time and space complexity

All methods shown run in O(1) time (constant time) and use O(1) extra space. Tuple unpacking conceptually creates a small temporary tuple (constant-size), but in practice this cost is negligible for two values.