Beginner Logical Thinking Python

Swap Two Numbers in Python (3 Ways)

Exchange the values of two variables in Python using a temporary variable, arithmetic, and tuple assignment.

  • TimeO(1)
  • SpaceO(1)
  • Hints3
  • Read4 min
Quick answer

In Python the simplest way to swap two variables is a, b = b, a. Python builds a tuple of the right-hand values first, then assigns them, so no temporary variable is needed. The classic ways also work: temp = a; a = b; b = temp, or without a temp variable a = a + b; b = a - b; a = a - b. Use the tuple swap in real code.

AssignmentArithmetic operatorsTuple packing and unpackingFunctions returning two values
1

Problem statement

Write a program to swap two numbers in Python. Given a = 10 and b = 20, after the swap a should be 20 and b should be 10.

Show three methods: a temporary variable, addition and subtraction (no temp variable), and Python's tuple swap.

Input

Two values a and b.

Output

The values of a and b before and after the swap.

Examples

Example 1
Inputa = 10, b = 20
Outputa = 20, b = 10

Each variable now holds the value the other one had.

Example 2
Inputa = "apple", b = "mango" (tuple swap)
Outputa = "mango", b = "apple"

Tuple swap works for any type, not only numbers.

Constraints

  • The arithmetic method works only for numbers
  • The temp and tuple methods work for any values, including strings and lists
2

Think before you code

Reveal the questions to ask yourself first
  • If you write a = b first, what happens to the old value of a?
  • If a holds a + b, how can you get the old a back?
  • Does Python need the right side of a, b = b, a to be computed before assigning?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Save a in temp before overwriting it.
2 Hint 2
For the arithmetic method: a = a + b, then b = a - b gives the old a, then a = a - b gives the old b.
3 Hint 3
In Python, a, b = b, a does the whole swap on one line.
4

Approach

Reveal the step-by-step approach

Method 1: temporary variable

temp = a   # keep a safe
a = b      # a gets b
b = temp   # b gets the old a

This works in every language and for every type. It is the safest method to explain.

Method 2: swap without temp variable in Python (arithmetic)

a = a + b   # a holds the sum
b = a - b   # sum - old b = old a
a = a - b   # sum - old a = old b

Python integers do not overflow, so this is safe for whole numbers of any size. For decimals, small rounding errors can appear (see below).

Method 3: tuple swap in Python

a, b = b, a

Python evaluates the right side first and packs it into the tuple (b, a), using the old values. Then it unpacks that tuple into a and b. This is the Pythonic way.

Method Works for strings and lists? Risk
temp variable Yes None
+ and - No, numbers only Rounding error with floats
tuple swap Yes None
5

Dry run

Walk through the example step by step

Arithmetic method, a = 10, b = 20:

step       | a  | b
-----------+----+----
start      | 10 | 20
a = a + b  | 30 | 20
b = a - b  | 30 | 10
a = a - b  | 20 | 10

Tuple swap, a = 20, b = 10:

right side b, a is evaluated -> (10, 20)
unpack: a = 10, b = 20
6

Solution

Reveal the full Python solution
solution.py
a = 10
b = 20
print("Before swap: a =", a, "b =", b)

# Method 1: temporary variable
temp = a
a = b
b = temp
print("After temp swap: a =", a, "b =", b)

# Method 2: addition and subtraction
a = a + b
b = a - b
a = a - b
print("After arithmetic swap: a =", a, "b =", b)

# Method 3: tuple swap
a, b = b, a
print("After tuple swap: a =", a, "b =", b)

Output:

Before swap: a = 10 b = 20
After temp swap: a = 20 b = 10
After arithmetic swap: a = 10 b = 20
After tuple swap: a = 20 b = 10

Each method swaps the current values, so the program flips back and forth: the second swap undoes the first, and the third swaps again.

Swap two values entered by the user

a = input("Enter a: ")
b = input("Enter b: ")
a, b = b, a
print("a =", a)
print("b =", b)
Enter a: apple
Enter b: mango
a = mango
b = apple

No int() is needed here, because the tuple swap does not care about the type.

Swapping variables of any type, and list items

x, y = 3.5, "hello"
x, y = y, x
print(x, y)

nums = [10, 20, 30, 40]
nums[0], nums[3] = nums[3], nums[0]
print(nums)
hello 3.5
[40, 20, 30, 10]

Swapping two list items this way is used in every sorting program, such as selection sort.

Why arithmetic swap is risky with decimals

a, b = 0.1, 0.2
a = a + b
b = a - b
a = a - b
print(a, b)
0.2 0.10000000000000003

Floats are stored in binary, so 0.1 + 0.2 - 0.2 is not exactly 0.1. The tuple swap has no such problem.

XOR swap and swapping inside a function

a, b = 5, 9
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b)
9 5

XOR works only for integers. It is asked in C interviews more than in Python ones.

def swap(a, b):
    a, b = b, a


x, y = 1, 2
swap(x, y)
print(x, y)


def swapped(a, b):
    return b, a


x, y = swapped(x, y)
print(x, y)
1 2
2 1

The first function swaps only its own local names, so x and y do not change. Return the two values and assign them back, as the second function does.

The C version is swap two numbers without a third variable in C, and the Java version is swap two numbers without using a third variable.

TimeO(1)
SpaceO(1)
7

Review before the interview

Common mistakes

  • Writing a = b then b = a. Both end up with the old b, because the old a is lost on the first line.
  • Changing the order of the arithmetic lines. b = a - b must come after a = a + b.
  • Using the arithmetic method on strings. "apple" + "mango" works, but "applemango" - "mango" raises TypeError.
  • Expecting a swap(a, b) function to change the caller's variables. Return the values instead.

Edge cases to test

  • Equal values: all three methods leave both as they are.
  • Negative numbers work with all three methods.
  • Floats: the arithmetic method can leave tiny rounding errors such as 0.10000000000000003.

Interview follow-ups

  • How would you swap three variables so that a gets b, b gets c and c gets a?
  • How would you swap the first and last digits of a number?
  • Why does XOR swapping fail if both names point to the same memory in C?

Keep practising

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us