Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to swap two numbers without using third variable
Swapping the values of two variables is a common operation in programming. Typically, the swap is performed using a third variable to temporarily store one of the values. However, there are several clever techniques to swap two numbers without using an additional variable, which can be useful for memory optimization or in constrained environments.
In this article, we will explore different Python approaches to swap two numbers without using a third variable, including arithmetic operations and bitwise XOR operations.
Method 1: Using Arithmetic Operations (Addition and Subtraction)
This method uses basic arithmetic to swap values ?
def swap_using_arithmetic(a, b):
print(f"Before swapping: a = {a}, b = {b}")
# Swap using addition and subtraction
a = a + b # a now contains sum of both numbers
b = a - b # b now contains original value of a
a = a - b # a now contains original value of b
print(f"After swapping: a = {a}, b = {b}")
return a, b
# Testing the function
a, b = 15, 25
swap_using_arithmetic(a, b)
Before swapping: a = 15, b = 25 After swapping: a = 25, b = 15
Method 2: Using XOR Bitwise Operation
The XOR approach uses bitwise exclusive OR operation. XOR returns 1 if the corresponding bits are different, and 0 if they are the same ?
def swap_using_xor(a, b):
print(f"Before swapping: a = {a}, b = {b}")
# Swap using XOR operations
a = a ^ b # a contains XOR of both numbers
b = a ^ b # b now contains original value of a
a = a ^ b # a now contains original value of b
print(f"After swapping: a = {a}, b = {b}")
return a, b
# Testing the function
a, b = 10, 5
swap_using_xor(a, b)
Before swapping: a = 10, b = 5 After swapping: a = 5, b = 10
Method 3: Using Multiplication and Division
This method works with multiplication and division, but requires that neither number is zero ?
def swap_using_multiplication(a, b):
if a == 0 or b == 0:
print("This method doesn't work with zero values")
return a, b
print(f"Before swapping: a = {a}, b = {b}")
# Swap using multiplication and division
a = a * b
b = a // b # Using integer division
a = a // b
print(f"After swapping: a = {a}, b = {b}")
return a, b
# Testing the function
a, b = 6, 4
swap_using_multiplication(a, b)
Before swapping: a = 6, b = 4 After swapping: a = 4, b = 6
Method 4: Python Tuple Unpacking (Pythonic Way)
While not technically avoiding a temporary variable (Python creates one internally), this is the most Pythonic approach ?
def swap_pythonic(a, b):
print(f"Before swapping: a = {a}, b = {b}")
# Swap using tuple unpacking
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")
return a, b
# Testing the function
a, b = 100, 200
swap_pythonic(a, b)
Before swapping: a = 100, b = 200 After swapping: a = 200, b = 100
Comparison of Methods
| Method | Pros | Cons | Best For |
|---|---|---|---|
| Arithmetic (+/-) | Simple, works with all numbers | Risk of integer overflow | Small integers |
| XOR Bitwise | No overflow risk, works with integers | Only works with integers | Integer swapping |
| Multiplication (/) | Mathematical approach | Doesn't work with zero | Non-zero numbers |
| Tuple Unpacking | Readable, Pythonic | Uses temporary variable internally | General Python programming |
Complete Example
Here's a complete program demonstrating all methods ?
def demonstrate_all_swaps():
original_a, original_b = 12, 8
print("=== Demonstrating All Swap Methods ===\n")
# Method 1: Arithmetic
print("1. Arithmetic Method:")
a, b = original_a, original_b
a = a + b
b = a - b
a = a - b
print(f"Result: a = {a}, b = {b}\n")
# Method 2: XOR
print("2. XOR Method:")
a, b = original_a, original_b
a = a ^ b
b = a ^ b
a = a ^ b
print(f"Result: a = {a}, b = {b}\n")
# Method 3: Pythonic
print("3. Pythonic Method:")
a, b = original_a, original_b
a, b = b, a
print(f"Result: a = {a}, b = {b}")
demonstrate_all_swaps()
=== Demonstrating All Swap Methods === 1. Arithmetic Method: Result: a = 8, b = 12 2. XOR Method: Result: a = 8, b = 12 3. Pythonic Method: Result: a = 8, b = 12
Conclusion
While multiple methods exist to swap numbers without a third variable, the XOR method is most commonly used for integers due to its efficiency and no overflow risk. For general Python programming, tuple unpacking (a, b = b, a) is the preferred Pythonic approach.
