How to Swap Two Numbers in Python (With and Without a Function)

To swap two numbers in Python, use tuple unpacking: a, b = b, a. It is one line, works for any type (integers, floats, strings, list items) and needs no temporary variable. This guide shows that and the classic alternatives (a temporary variable, arithmetic and XOR), explains how swapping works inside a function, and includes a complete program for swapping two numbers entered by the user.

All examples were run with Python 3.12.5 in the Windows Command Prompt. The Python docs explain the underlying feature under tuples and sequence unpacking.

Swap two numbers in one line

a = 5
b = 9
a, b = b, a          # swap in one line
print("a =", a, "b =", b)

Output:

a = 9 b = 5

The right side b, a is evaluated first and packed into a tuple (9, 5); then the tuple is unpacked into a and b. Because both values are read before anything is assigned, nothing is overwritten.

Four ways to swap two numbers

# 1. tuple unpacking (the Pythonic way)
a, b = 5, 9
a, b = b, a
print("tuple unpacking:", a, b)

# 2. a temporary variable
a, b = 5, 9
temp = a
a = b
b = temp
print("temp variable:  ", a, b)

# 3. arithmetic (+ and -)
a, b = 5, 9
a = a + b
b = a - b
a = a - b
print("arithmetic:     ", a, b)

# 4. bitwise XOR (integers only)
a, b = 5, 9
a ^= b
b ^= a
a ^= b
print("XOR:            ", a, b)

Output:

tuple unpacking: 9 5
temp variable:   9 5
arithmetic:      9 5
XOR:             9 5
Command Prompt output of a Python program swapping two numbers with tuple unpacking, a temporary variable, arithmetic and bitwise XOR
All four methods give the same result for integers.
MethodCodeWorks forNotes
Tuple unpackinga, b = b, aAny typeRecommended
Temporary variablet = a; a = b; b = tAny typeWorks in every language
Arithmetica = a + b; b = a - b; a = a - bNumbersFloats can lose precision
XORa ^= b; b ^= a; a ^= bIntegers onlyA classic interview trick

Why arithmetic swapping is risky with floats

a, b = 0.1, 0.7
a = a + b
b = a - b
a = a - b
print("arithmetic swap:", a, b)        # rounding errors creep in

a, b = 0.1, 0.7
a, b = b, a
print("tuple swap:     ", a, b)        # exact

x, y = "cat", "dog"
x, y = y, x                             # works for any type, not just numbers
print("strings:        ", x, y)

Output:

arithmetic swap: 0.7 0.09999999999999998
tuple swap:      0.7 0.1
strings:         dog cat
Command Prompt output showing an arithmetic swap of 0.1 and 0.7 producing rounding errors while tuple swapping stays exact
Adding and subtracting floats introduces rounding errors; tuple unpacking just moves the values.

Swap two numbers using a function

A function cannot change the caller’s variables by rebinding its parameters, because Python passes references to objects, and assigning inside the function only changes the local names. Return the swapped values and assign them:

def swap(x, y):
    """Return the two values in reverse order."""
    return y, x


def swap_inside(x, y):
    x, y = y, x          # only swaps the LOCAL names x and y


a, b = 5, 9
swap_inside(a, b)
print("after swap_inside:", a, b)      # unchanged

a, b = swap(a, b)                       # assign the returned tuple
print("after swap:       ", a, b)

Output:

after swap_inside: 5 9
after swap:        9 5
Command Prompt output showing that swapping inside a Python function leaves the caller's variables unchanged while returning a tuple works
swap_inside() changes nothing; a, b = swap(a, b) works.

Python program to swap two numbers entered by the user

a = input("Enter the first number: ")
b = input("Enter the second number: ")

a, b = float(a), float(b)
print(f"Before swapping: a = {a:g}, b = {b:g}")
a, b = b, a
print(f"After swapping:  a = {a:g}, b = {b:g}")

Output (the user typed 12 and 7.5):

Enter the first number: 12
Enter the second number: 7.5
Before swapping: a = 12, b = 7.5
After swapping:  a = 7.5, b = 12
Command Prompt running a Python program that asks for two numbers, the user types 12 and 7.5, and it prints them before and after swapping
The program running with numbers typed in the Command Prompt.

Swap items in a list or dictionary

scores = [40, 75, 90, 60]
scores[0], scores[2] = scores[2], scores[0]      # swap two elements of a list
print(scores)

prices = {"apple": 1.2, "mango": 2.5}
prices["apple"], prices["mango"] = prices["mango"], prices["apple"]   # swap two dictionary values
print(prices)

Output:

[90, 75, 40, 60]
{'apple': 2.5, 'mango': 1.2}

How a, b = b, a works

The bytecode shows what really happens: in CPython 3.12 the compiler does not even build a tuple for a two-name swap. It loads b and a onto the stack and stores them back in the opposite order:

import dis

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

dis.dis(swap)          # show the bytecode behind a, b = b, a

Output:

  3           0 RESUME                   0

  4           2 LOAD_FAST                1 (b)
              4 LOAD_FAST                0 (a)
              6 STORE_FAST               1 (b)
              8 STORE_FAST               0 (a)

  5          10 LOAD_FAST                0 (a)
             12 LOAD_FAST                1 (b)
             14 BUILD_TUPLE              2
             16 RETURN_VALUE

More simple Python programs:

Frequently asked questions

How do I swap two numbers in Python?

Use a, b = b, a. The right side is evaluated first, so no temporary variable is needed.

How do I swap two numbers without a third variable?

Tuple unpacking (a, b = b, a) needs no third variable. For integers, the arithmetic and XOR tricks also work.

Is there a swap function in Python?

No built-in one, and you do not need it. Write def swap(x, y): return y, x and call a, b = swap(a, b).

Why does swapping inside a function not change my variables?

Assigning to parameters only changes the function’s local names. Return the swapped values and assign them in the caller.

How do I swap two elements in a list?

items[i], items[j] = items[j], items[i].

Is the arithmetic swap safe for decimals?

No. With floats, a + b - b can differ from a because of rounding. Use tuple unpacking.