How to swap two numbers in Python

Discover multiple ways to swap two numbers in Python. Explore tips, real-world uses, and how to debug common errors in your code.

How to swap two numbers in Python
Published on: 
Fri
Feb 20, 2026
Updated on: 
Mon
Apr 6, 2026
The Replit Team

You will often need to swap two numbers in Python. This operation is essential for sort algorithms and data manipulation. Python provides several elegant methods to accomplish this with minimal code.

In this article, we'll explore various techniques to swap numbers. We will cover practical tips, show real-world applications, and offer advice to debug common issues you might face.

Using a temporary variable

a = 10
b = 20
temp = a
a = b
b = temp
print(f"After swapping: a = {a}, b = {b}")--OUTPUT--After swapping: a = 20, b = 10

This classic approach is common in many programming languages. It uses a third variable to prevent data loss during the swap. Here's how it works:

  • The value of a is first copied to a placeholder variable, temp.
  • With its original value safely stored, a is updated with the value of b.
  • Finally, b takes the value that was originally in a, which is now held by temp.

This three-step shuffle ensures that neither value is accidentally overwritten in the process.

Python-specific swapping techniques

While the temporary variable method works everywhere, Python offers more concise solutions like tuple unpacking (a, b = b, a), arithmetic (+, -), or the bitwise XOR operator (^).

Using Python's a, b = b, a syntax

a = 10
b = 20
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")--OUTPUT--After swapping: a = 20, b = 10

This technique is a Python-native feature known as tuple unpacking. It's a concise and highly readable way to swap variables. The expression on the right side, b, a, creates a new tuple in memory with the values of the variables in reversed order.

  • Python evaluates the right-hand side first, creating a temporary tuple like (20, 10).
  • It then unpacks the values from this tuple into the variables on the left-hand side, assigning 20 to a and 10 to b.

This entire swap happens in a single, atomic operation, eliminating the need for a temporary variable.

Using arithmetic operations (+ and -)

a = 10
b = 20
a = a + b # a becomes 30
b = a - b # b becomes 10
a = a - b # a becomes 20
print(f"After swapping: a = {a}, b = {b}")--OUTPUT--After swapping: a = 20, b = 10

You can also swap numbers using a clever arithmetic trick. This method avoids a temporary variable by storing the sum of both numbers in one of the variables first. The swap unfolds in three steps:

  • First, a = a + b combines both values into a.
  • Next, b = a - b subtracts the original b from this new sum, which leaves the original value of a in b.
  • Finally, a = a - b subtracts the new value of b from the sum, leaving the original value of b in a.

While this works for integers, be mindful of potential overflow issues if you're working with extremely large numbers.

Using the XOR bitwise operator (^)

a = 10
b = 20
a = a ^ b
b = a ^ b
a = a ^ b
print(f"After swapping: a = {a}, b = {b}")--OUTPUT--After swapping: a = 20, b = 10

The XOR swap is a clever, memory-efficient trick that manipulates the binary representations of numbers. The XOR operator (^) returns a 1 if two bits are different and a 0 if they're the same. This unique property lets you swap values without a temporary variable.

  • First, a = a ^ b stores the bitwise combination of both numbers in a.
  • Then, b = a ^ b cancels out the original b bits, leaving b with a's original value.
  • Finally, a = a ^ b does the same for a, leaving it with b's original value.

Advanced swapping techniques

These swapping principles aren't limited to simple variables; you can apply similar powerful idioms to manipulate elements within data structures or use dedicated modules.

Swapping list elements with list[i], list[j] = list[j], list[i]

numbers = [10, 20, 30, 40]
numbers[0], numbers[3] = numbers[3], numbers[0]
print(f"List after swapping: {numbers}")--OUTPUT--List after swapping: [40, 20, 30, 10]

Python’s elegant tuple unpacking extends directly to list elements, offering a highly readable way to rearrange items. This method lets you swap values at specific indices in a single, expressive line of code.

  • The statement numbers[0], numbers[3] = numbers[3], numbers[0] pinpoints the elements at index 0 and 3.
  • It then swaps their values in one atomic operation, just as it does with standalone variables.

This technique is a cornerstone of many sorting algorithms where exchanging items is a fundamental step.

Swapping dictionary keys and values

original = {'a': 1, 'b': 2}
swapped = {value: key for key, value in original.items()}
print(f"Original: {original}\nSwapped: {swapped}")--OUTPUT--Original: {'a': 1, 'b': 2}
Swapped: {1: 'a', 2: 'b'}

You can flip a dictionary’s keys and values using a dictionary comprehension. This is a concise and readable way to create a new dictionary based on an existing one. The expression {value: key for key, value in original.items()} iterates over each key-value pair from the original dictionary.

  • The .items() method provides each key-value pair for the loop.
  • The comprehension then builds a new dictionary, using the original value as the new key and the original key as the new value.

Just remember that this approach requires all values in the original dictionary to be unique and hashable, since they'll become the new keys.

Using the operator module

import operator
a = 10
b = 20
a, b = operator.itemgetter(1, 0)([a, b])
print(f"After swapping: a = {a}, b = {b}")--OUTPUT--After swapping: a = 20, b = 10

The operator module offers a functional approach to swapping. The operator.itemgetter(1, 0) function creates a callable that fetches items from a sequence at specified indices—in this case, grabbing the item at index 1 first, then index 0.

  • When you call this on a temporary list like [a, b], it returns a tuple with the elements in reversed order.
  • This resulting tuple is then unpacked back into a and b, completing the swap.

While more verbose than simple tuple unpacking, this method is powerful when you need to pass a callable to another function, such as a sort key.

Move faster with Replit

Replit is an AI-powered development platform that comes with all dependencies pre-installed, so you can skip setup and start coding Python instantly.

Instead of piecing together techniques like the a, b = b, a swap, you can use Agent 4 to build complete applications. Describe the app you want to build, and the Agent takes it from idea to working product by handling the code, databases, APIs, and deployment:

  • A data-mapping utility that reverses key-value pairs in a configuration file, allowing for bidirectional lookups.
  • A playlist shuffler that implements a sorting algorithm, repeatedly swapping song positions using the list[i], list[j] = list[j], list[i] idiom.
  • A simple settings tool that toggles between two states by swapping the primary and secondary color values in a theme file.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While Python's swapping techniques are powerful, you can run into subtle bugs with mutable objects, None values, or mismatched data types.

Avoiding reference confusion when swapping mutable objects

When you're swapping mutable objects like lists or dictionaries, it's easy to get tangled in reference confusion. Unlike simple numbers, these variables are just pointers to objects in memory. If you swap them incorrectly, you might end up with two variables pointing to the same object, causing changes in one to unexpectedly affect the other.

The standard a, b = b, a idiom swaps the references, which is usually what you want. But if your goal is to swap the contents of two lists without changing which variable points to which original list shell, you'd need a different approach—perhaps swapping the contents element by element or creating deep copies.

Handling None values safely during swapping

Swapping can get tricky when None values are involved. Methods that rely on arithmetic, like the addition and subtraction trick, will immediately raise a TypeError because you can't perform math operations on a None type. The same goes for the bitwise XOR swap.

The most reliable way to handle potential None values is to use tuple unpacking. The a, b = b, a syntax is completely agnostic about the data it's moving. It simply reassigns the variable names to the objects, so it works flawlessly whether you're swapping integers, strings, or None.

Handling type errors when swapping different data types

Type errors are another common hurdle, especially if you're using arithmetic or bitwise swaps. These techniques assume you're working with compatible types—specifically, numbers. If you try to swap an integer and a string using a = a + b, Python will throw a TypeError because it doesn't know how to add them.

Once again, tuple unpacking is your best defense. The a, b = b, a syntax is a universal solution that works regardless of data type because it never attempts to perform operations on the values, making it the most robust choice for swapping items of different types.

Avoiding reference confusion when swapping mutable objects

When swapping mutable objects like lists, it's easy to create a reference trap. Instead of swapping the list contents, you might accidentally make both variables point to the same object in memory. The code below shows how this common error occurs.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1 = list2
list2 = list1
print(f"After swapping: list1 = {list1}, list2 = {list2}")

The assignment list1 = list2 causes both variables to point to the same list. The next line, list2 = list1, is now redundant, and the original data from list1 is lost. See the correct approach below.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1, list2 = list2, list1
print(f"After swapping: list1 = {list1}, list2 = {list2}")

The first attempt fails because list1 = list2 makes both variables point to the same list, causing the original [1, 2, 3] to be lost. The correct solution uses tuple unpacking with list1, list2 = list2, list1. This idiom swaps the references themselves, ensuring each variable now points to the other's original list. It's the proper way to swap mutable objects like lists and dictionaries without causing unexpected side effects.

Handling None values safely during swapping

Arithmetic-based swaps fail when one of the variables is None. Since you can't perform mathematical operations like addition on a None type, Python will raise a TypeError. The following code shows what happens when you try this approach.

a = 10
b = None
a = a + b
b = a - b
a = a - b
print(f"After swapping: a = {a}, b = {b}")

The operation a = a + b fails because Python cannot add an integer to a None type, which triggers a TypeError. The following code demonstrates a robust approach that avoids this issue entirely.

a = 10
b = None
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")

The tuple unpacking syntax, a, b = b, a, is the safest way to swap variables that might be None. This method simply reassigns the variable names to the underlying objects without performing any operations on their values. It's completely agnostic to the data type, so it works flawlessly with integers, strings, or None. This makes it the most robust choice when you can't guarantee the data types you're handling.

Handling type errors when swapping different data types

Arithmetic-based swaps, like those using the + and - operators, require compatible data types. If you try to swap a string and an integer, Python can't perform the math and will raise a TypeError. The code below demonstrates this common pitfall.

a = "10"
b = 20
a = a + b
b = a - b
a = a - b
print(f"After swapping: a = {a}, b = {b}")

The code fails at a = a + b because the + operator can't add a string to an integer, triggering a TypeError. The correct approach, shown next, handles different data types without issue.

a = "10"
b = 20
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")

Using a, b = b, a is the most reliable way to swap variables of different types. This Python-native feature works by reassigning the variable names to their new objects, rather than performing any mathematical operations on the values themselves. You should always prefer this method when you can't be sure your variables are of the same type, as it sidesteps any potential TypeError issues entirely.

Real-world applications

Beyond avoiding common errors, these swapping idioms are crucial for algorithms like bubble_sort() and methods for randomizing data.

Swapping in sorting algorithms with bubble_sort()

The bubble_sort() algorithm is a classic example of this principle in action, where adjacent list elements are repeatedly compared and swapped until the entire list is sorted.

def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr) - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr

numbers = [64, 34, 25, 12, 22]
print(f"Sorted array: {bubble_sort(numbers)}")

The bubble_sort() function uses a nested loop to organize the list. The inner loop iterates through the array, comparing each element to the one immediately following it.

  • If an element is greater than its neighbor, their positions are swapped using the concise arr[j], arr[j + 1] = arr[j + 1], arr[j] syntax.
  • This process effectively "bubbles" the largest unsorted values toward the end of the list with each pass.

The outer loop repeats this entire process, ensuring the list is fully sorted by the end. With vibe coding, you can describe sorting algorithms like this and let AI generate the implementation for you.

Randomizing elements with the Fisher-Yates shuffle

Another powerful application of swapping is in the Fisher-Yates shuffle, an algorithm that efficiently randomizes a list's elements.

import random
random.seed(42) # For consistent output in this example
deck = ['A♠', 'K♠', 'Q♠', 'J♠', '10♠']
for i in range(len(deck) - 1, 0, -1):
j = random.randint(0, i)
deck[i], deck[j] = deck[j], deck[i]
print(f"Shuffled deck: {deck}")

This code implements the Fisher-Yates shuffle to randomize the deck list. The for loop iterates backward, effectively building the shuffled list from the end to the beginning. The random.seed() function is used here simply to make the outcome predictable for this example.

  • At each step i, an element is randomly chosen from the front of the list—from index 0 to i.
  • This chosen element is then swapped into the i-th position, locking it into its final, shuffled place.

This method ensures that by the end, every card has been placed randomly. Complex algorithms like this are perfect candidates for AI coding assistance in Python.

Get started with Replit

Put these swapping techniques into practice with Replit Agent. Describe a tool like, "a script to sort numbers with bubble sort," or "a program to shuffle a list of items randomly."

The Agent writes the code, tests for errors, and deploys the app directly from your description. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.