Table of contents
1.
Introduction
2.
Basic Example
2.1.
Python
3.
Method 1: Using a Temporary Variable
3.1.
Python
4.
Method 2: Using Bitwise XOR Operator
4.1.
Python
5.
Method 3: Using Addition and Subtraction Operators
5.1.
Python
6.
Method 4: Using Division and Multiplication Operators
6.1.
Python
7.
Method 5: Using Both Bitwise Operators & Arithmetic Operators
7.1.
Python
8.
Frequently Asked Questions
8.1.
Can I swap numbers in Python without using a third variable?
8.2.
Is it better to use arithmetic operations or the bitwise XOR for swapping?
8.3.
Will these swapping methods work with floating-point numbers?
9.
Conclusion
Last Updated: Mar 31, 2024
Easy

Swap Two Numbers in Python

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Swapping two numbers is a fundamental concept in programming, especially for new coders understanding algorithms and data manipulation. This simple but important operation involves exchanging the values of two variables. 

Swap Two Numbers in Python

In this article, we'll learn various techniques to achieve this in Python, a versatile and widely-used programming language. From basic methods to more advanced techniques using bitwise operators, we'll learn everything. 

Basic Example

Imagine you have two cups, one filled with apple juice and the other with orange juice. Your goal is to swap the contents without using a third cup. This scenario mirrors our objective with numbers in Python. Let's say we have two variables, a with a value of 5 and b with a value of 10. Our task is to swap these values so that a becomes 10 and b becomes 5, a basic swapping 

  • Python

Python

# Initial values
a = 5
b = 10

print("Before swapping:")
print("a =", a, "& b =", b)

# Swapping logic will go here

print("After swapping:")
print("a =", a, "& b =", b)
You can also try this code with Online Python Compiler
Run Code

Output

Before swapping:
a = 5 & b = 10
After swapping:
a = 5 & b = 10


In this setup, the 'Before swapping' part shows the original values, and the 'After swapping' part will show the new values once we apply our swapping logic in the next sections.

Method 1: Using a Temporary Variable

The most straightforward way to swap two numbers is by using a third variable, often called a 'temporary' or 'temp' variable. This method is like using an empty cup to hold one of the juices while you pour the other into its place. Here's how it works in Python:

  • Store the value of a in the temporary variable.
     
  • Assign the value of b to a.
     
  • Assign the value stored in the temporary variable to b.
     

Here's the code:

  • Python

Python

# Initial values
a = 5
b = 10

print("Before swapping:")
print("a =", a, "& b =", b)

# Swapping using a temporary variable
temp = a # Step 1
a = b # Step 2
b = temp # Step 3

print("After swapping:")
print("a =", a, "& b =", b)
You can also try this code with Online Python Compiler
Run Code

Output

Before swapping:
a = 5 & b = 10
After swapping:
a = 5 & b = 10


After executing this code, a will hold the value 10, and b will hold the value 5, effectively swapping their contents. This method is simple and easy to understand, making it a great starting point for beginners.

Method 2: Using Bitwise XOR Operator

This method uses the bitwise XOR (^) operator. XOR is a logical operation that outputs true only when the inputs differ. In terms of numbers, it does a bit-by-bit comparison and sets each bit to 1 if the bits at that position in the two operands are different.

Here's how you can use XOR to swap two numbers:

  • XOR a and b, and store the result in a.
     
  • XOR the new a with b, and store the result in b.
     
  • XOR the new b with a, and store the result in a.
     

This might sound confusing, but it's quite straightforward in practice. Here's the code:

  • Python

Python

# Initial values
a = 5
b = 10

print("Before swapping:")
print("a =", a, "& b =", b)

# Swapping using bitwise XOR
a = a ^ b # Step 1
b = a ^ b # Step 2
a = a ^ b # Step 3

print("After swapping:")
print("a =", a, "& b =", b)
You can also try this code with Online Python Compiler
Run Code

Output

Before swapping:
a = 5 & b = 10
After swapping:
a = 5 & b = 10


After running this code, a will become 10 and b will become 5. The beauty of this method is that it doesn't require extra space for a temporary variable, and it's quite efficient.

Method 3: Using Addition and Subtraction Operators

Another useful and important way to swap two numbers without a temporary variable involves using basic arithmetic: addition and subtraction. This method works on a simple mathematical principle where the sum of two numbers is manipulated to isolate and swap their original values.

Here’s the step-by-step process:

  • Add the value of b to a and store the result in a. Now, a contains the total of the original a and b.
     
  • Subtract the new value of a (which is a + b) by the original b to get the original a, and assign this to b.
     
  • Subtract the new value of b (which is the original a) from the new a (which is a + b) to get the original b, and assign this back to a.
     

This might sound a bit confusing, but the code makes it clear:

  • Python

Python

# Initial values
a = 5
b = 10

print("Before swapping:")
print("a =", a, "& b =", b)

# Swapping using addition and subtraction
a = a + b # Step 1
b = a - b # Step 2
a = a - b # Step 3

print("After swapping:")
print("a =", a, "& b =", b)
You can also try this code with Online Python Compiler
Run Code

Output

Before swapping:
a = 5 & b = 10
After swapping:
a = 5 & b = 10


Executing this code swaps the values of a and b using just addition and subtraction, eliminating the need for a third, temporary storage variable. It's a straightforward and efficient method, especially for numerical operations.

Method 4: Using Division and Multiplication Operators

This method is similar to the addition and subtraction technique but uses different operations. The main idea is to manipulate the product and quotient of the two numbers to reverse their values.

Here's how it works:

  • Multiply a by b and store the result in a. Now a holds the product of the original a and b.
     
  • Divide the new a (which is a * b) by the original b to retrieve the original a, and assign this to b.
     
  • Divide the new a (which is still a * b) by the new b (which is the original a) to get the original b, and assign this back to a.
     

Let's look at the code for a clearer understanding:

  • Python

Python

# Initial values
a = 5
b = 10

# Ensure neither a nor b is zero
if a != 0 and b != 0:
print("Before swapping:")
print("a =", a, "& b =", b)

# Swapping using multiplication and division
a = a * b # Step 1
b = a / b # Step 2
a = a / b # Step 3

print("After swapping:")
print("a =", a, "& b =", b)
else:
print("This method cannot be used if either number is zero.")
You can also try this code with Online Python Compiler
Run Code

Output

Before swapping:
a = 5 & b = 10
After swapping:
a = 10.0 & b = 5.0


This approach effectively swaps the values of a and b without needing an additional variable for storage, using the properties of multiplication and division. It's a neat trick, but the caveat of avoiding zero is important to remember.

Method 5: Using Both Bitwise Operators & Arithmetic Operators

For those who like to blend concepts, there's a way to swap numbers that combines the cleverness of bitwise XOR with the straightforwardness of arithmetic operations. This hybrid approach is not commonly used but offers an interesting perspective on how different programming concepts can intersect.

Here's the process broken down:

  • Start with the XOR operation to initiate the swap, setting a to a XOR b.
     
  • Use an arithmetic operation (addition, in this case) to update b, making it b + a (now, a is a XOR b from step 1).
     
  • Apply XOR again, this time to b, to finalize the swap, setting a back to its original value and thus completing the swap.
     

This code illustrates the method:

  • Python

Python

# Initial values
a = 5
b = 10

print("Before swapping:")
print("a =", a, "& b =", b)

# Swapping using a combination of bitwise and arithmetic operators
a = a ^ b # Step 1: Start with XOR
b = b ^ a # Step 2: Apply XOR again
a = a ^ b # Step 3: Apply XOR again

print("After swapping:")
print("a =", a, "& b =", b)
You can also try this code with Online Python Compiler
Run Code

 

Output

Before swapping:
a = 5 & b = 10
After swapping:
a = 10 & b = 5


This method showcases how you can creatively combine different operations to achieve a goal in programming. It's a testament to the flexibility and versatility of coding, where multiple paths can lead to the same destination.

Frequently Asked Questions

Can I swap numbers in Python without using a third variable?

Yes, you can swap numbers without a third variable using methods like the bitwise XOR operator or arithmetic operations (addition and subtraction, or multiplication and division), as demonstrated in the methods above.

Is it better to use arithmetic operations or the bitwise XOR for swapping?

It depends on the context and your preference. The bitwise XOR is neat and can be faster, but it's less intuitive. Arithmetic methods are more straightforward but ensure you're not dividing by zero in the multiplication/division method.

Will these swapping methods work with floating-point numbers?

Yes, these methods work with floating-point numbers as well, but be mindful of potential precision loss with floating-point arithmetic, especially with the multiplication/division method.

Conclusion

In this article, we've learned several ways to swap two numbers in Python, starting with the simple method of using a temporary variable and progressing to more sophisticated techniques involving bitwise XOR and arithmetic operations. Each method has its own advantages and disadvanatges, offering a blend of simplicity, efficiency, and a peek into the underlying mathematical principles. Understanding these various approaches not only enhances your problem-solving toolkit but also deepens your appreciation for the versatility and power of programming in Python. Whether you're preparing for exams, interviews, or just expanding your coding skills, mastering these methods is a valuable step forward in your journey.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass