Swapping two variables means exchanging their values so that each variable ends up holding the value the other one started with. If x = 10 and y = 50, then after swapping, x = 50 and y = 10. Python offers several ways to accomplish this, from a clean one-liner to the classic temporary variable approach used across programming languages.
Swapping variable values is one of the operations you will encounter early and often in programming. It shows up in sorting algorithms, data restructuring, coordinate manipulation, and countless other scenarios. In languages like C or Java, swapping typically requires a temporary variable to hold one value during the exchange. Python, however, gives you a much cleaner option. This article walks through every major approach so you can pick the right one for the job.
Tuple Unpacking (The Pythonic Way)
Tuple unpacking is the preferred method for swapping variables in Python. It is concise, readable, and eliminates the need for any extra variables. Under the hood, Python packs the right-hand side values into a temporary tuple, then unpacks them into the left-hand side targets. This all happens in a single statement.
x = 10
y = 50
x, y = y, x
print("x:", x) # Output: x: 50
print("y:", y) # Output: y: 10
When Python encounters x, y = y, x, it first evaluates the right side completely. It creates the tuple (50, 10) from the current values of y and x. Then it assigns the first element to x and the second to y. Because the right side is fully evaluated before any assignment happens, there is no risk of overwriting a value before it has been read.
Tuple unpacking works with any data type, not just integers. You can swap strings, floats, lists, or even objects the exact same way: a, b = b, a.
Using a Temporary Variable
The temporary variable approach is the traditional method used across nearly every programming language. You store one value in a third variable, overwrite the first variable, then assign the stored value to the second. It takes three lines instead of one, but it makes each step of the exchange explicit.
x = 10
y = 50
temp = x
x = y
y = temp
print("x:", x) # Output: x: 50
print("y:", y) # Output: y: 10
Here is what happens at each step. First, temp stores the original value of x, which is 10. Then x is reassigned to the current value of y, which is 50. Finally, y receives the value stored in temp, which is the original 10. The swap is complete.
While the temporary variable method is more verbose in Python, it is still the standard approach in many other languages. Understanding it will help if you ever work in C, Java, or JavaScript.
Arithmetic Operators
You can swap two numeric variables using addition and subtraction without introducing a third variable. This technique works by encoding both values into one of the variables, then extracting each original value back out through subtraction.
x = 10
y = 50
x = x + y # x is now 60
y = x - y # y is now 10 (the original x)
x = x - y # x is now 50 (the original y)
print("x:", x) # Output: x: 50
print("y:", y) # Output: y: 10
After the first line, x holds the sum of both original values (60). Subtracting the current y (still 50) from that sum produces 10, which is the original x. Then subtracting the new y (now 10) from x (still 60) produces 50, the original y.
The arithmetic approach only works with numeric types. It can also introduce floating-point precision errors with float values. For reliable swapping, stick with tuple unpacking.
A multiplication and division variant also exists, but it carries additional risks. Division by zero will crash your program if either variable is 0, and integer division (//) can produce incorrect results with negative numbers. The addition/subtraction version is safer, though tuple unpacking remains the recommended choice.
XOR Bitwise Swap
The XOR (exclusive or) operator provides another way to swap two integers without a temporary variable. It works because applying XOR twice with the same value restores the original number. This technique is a classic in computer science, frequently seen in low-level programming and technical interviews.
x = 10
y = 50
x = x ^ y # x now holds XOR of both
y = x ^ y # y now holds original x (10)
x = x ^ y # x now holds original y (50)
print("x:", x) # Output: x: 50
print("y:", y) # Output: y: 10
The XOR operator (^) compares each bit of two numbers. It returns 1 where the bits differ and 0 where they match. After x = x ^ y, the variable x contains a combined bit pattern. Applying XOR with y again extracts the original x, and one more XOR extracts the original y.
XOR swapping only works with integers. It will not work on floats, strings, or other data types. It also fails if both variables reference the same object in memory, since XORing a value with itself produces zero.
Swapping More Than Two Variables
Tuple unpacking scales naturally to three or more variables. Python evaluates the entire right-hand side before making any assignments, so you can rotate values through multiple variables in a single line.
a = 1
b = 2
c = 3
a, b, c = c, a, b
print("a:", a) # Output: a: 3
print("b:", b) # Output: b: 1
print("c:", c) # Output: c: 2
This rotates the values so that a gets the value that was in c, b gets the value that was in a, and c gets the value that was in b. The same pattern extends to four or more variables. Just list them in the order you want on both sides of the assignment.
# Swapping four variables
w, x, y, z = 1, 2, 3, 4
w, x, y, z = z, w, x, y
print(w, x, y, z) # Output: 4 1 2 3
Swapping Elements in a List
Tuple unpacking also works for swapping elements at specific positions in a list. This is especially useful inside sorting algorithms or when rearranging data.
numbers = [10, 20, 30, 40, 50]
# Swap the first and last elements
numbers[0], numbers[4] = numbers[4], numbers[0]
print(numbers) # Output: [50, 20, 30, 40, 10]
The syntax is identical to swapping standalone variables. Index into the list on both sides of the assignment, and Python handles the rest. This pattern appears in implementations of bubble sort, selection sort, and many other algorithms that rely on pairwise exchanges.
Use negative indexing for cleaner code when swapping end elements: numbers[0], numbers[-1] = numbers[-1], numbers[0]. This works regardless of the list length.
Key Takeaways
- Tuple unpacking is the standard: The expression
x, y = y, xis the idiomatic Python way to swap variables. It is clean, safe, and works with any data type. - Temporary variables still matter: The three-line
tempapproach is universal across programming languages. Knowing it builds a foundation that transfers to C, Java, and beyond. - Arithmetic and XOR swaps have limitations: Both techniques only work with numeric types (XOR is further restricted to integers), and they sacrifice readability for no meaningful performance gain in Python.
- Tuple unpacking scales: The same one-line syntax works for swapping three, four, or more variables and for exchanging elements at specific list indices.
- Performance differences are negligible: Modern Python optimizes all of these methods well. Choose the approach that makes your code the clearest, which in nearly every case is tuple unpacking.
Variable swapping is a small operation, but it appears constantly in real code -- from sorting algorithms to coordinate transformations to state management. Tuple unpacking gives you a tool that is both Pythonic and practical. Use it as your default, understand the alternatives for when you encounter them in other languages or interview questions, and move on to building the things that actually need those swapped values.