Python Program to Swap Two Numbers With Examples

In this article, we will learn about how to write python program to swap two numbers with examples.

Getting Started

The task is to swap two numbers using python programming. For example,

Let’s say a = 15 and b = 17, then output should be a = 17 and b = 15.

There are multiple ways to achieve above tasks.

  1. Using a Temporary Variable
  2. Using Arithmetic Operations
  3. Using Tuple Packing and Unpacking
  4. Using XOR bitwise operation
  5. Using map Function
  6. Using globals() function
  7. Using a class with instance variables
  8. Using setattr() function
  9. Using a Lambda Function and Dictionary
  10. Using a generator function
  11. Using deque Data Structure
  12. Using a Single Line of Code with Arithmetic Operations

1. Using a Temporary Variable

Here, we will use temporary variable to write python program to swap or interchange two numbers with examples.

def swap_numbers(a, b):
    temp = a # store value of a in temp.
    a = b   # store value of b in a.    
    b = temp  # store value of temp in b.
    return a, b

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

Here,

  • There are two variables a and b which we want to swap or interchange.
  • temp is temporary variable which is being used to store value of a temporarily.

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

2. Using Arithmetic Operations

We are going to use subtract i.e. and addition i.e. + operations to swap two numbers in python programming.

Here is how we can do it –

  • Take two variables a and b.
  • Then, take sum of a and b and store in a.
  • After that, subtract b from a and store in b.
  • Then, subtract b from a and store in a.
  • Now, value of a and b are interchanged value.

Program –

def swap_numbers(a, b):
    a = a + b  # Take sum of a and b and store in a.
    b = a - b  # Subtract b from a and store in b.
    a = a - b  # Subtract b from a and store in a.
    return a, b

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

3. Using Tuple Packing and Unpacking

We can also use techniques of tuple packing and unpacking to write python program to swap two numbers with examples as shown below –

def swap_numbers(a, b):
    return b, a

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

In above code, we are just interchanging the position and return the values.

Output

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

4. Using XOR Bitwise Operation

We can also use XOR bitwise operator i.e. ^ to interchange or swap two numbers in python as shown below –

def swap_numbers(a, b):
    a = a ^ b
    b = a ^ b
    a = a ^ b
    return a, b

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

5. Using map Function

We can also use map function in python to interchange or swap two numbers in python as shown below –

num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = map(lambda x: num2 if x == num1 else num1, (num1, num2))
print("After swap: num1 =", num1, "num2 =", num2)

Here,
We use the map function with a lambda function. Then, we compare each number with num1 and replaces it with num2 if it matches, and vice versa.

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

6. Using globals() Function

We can also use globals() function to swap two numbers in python with examples as shown below

def swap_numbers(a, b):
    globals()['num1'], globals()['num2'] = b, a

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

globals() allows us to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

So, here we have used this trick to interchange or swap variable a and b.

7. Using a Class with Instance Variables

There are some cases where we need to define variables in class and swap them. In such cases, we can swap them as shown below in python –

class NumberSwapper:
    def __init__(self, a, b):
        self.num1 = a
        self.num2 = b

    def swap(self):
        self.num1, self.num2 = self.num2, self.num1

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
swapper = NumberSwapper(num1, num2)
swapper.swap()
num1 = swapper.num1
num2 = swapper.num2
print("After swap: num1 =", num1, "num2 =", num2)

Here,
We have defined a class NumberSwapper with instance variables num1 and num2. The swap() method swaps the values of these variables.

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

8. Using setattr() Function

We can also use setattr() function to swap two numbers in python as shown below –

def swap_numbers(a, b):
    setattr(swap_numbers, 'num1', b)
    setattr(swap_numbers, 'num2', a)

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
swap_numbers(num1, num2)
num1 = swap_numbers.num1
num2 = swap_numbers.num2
print("After swap: num1 =", num1, "num2 =", num2)

Here,
We have used the setattr() function to dynamically set the values of num1 and num2 as attributes of the function itself.

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

9. Using a Lambda Function and Dictionary

We can also use lambda function and dictionary to write python program to swap two numbers with examples as shown below –

swap_numbers = lambda a, b: {'num1': b, 'num2': a}

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
result = swap_numbers(num1, num2)
num1 = result['num1']
num2 = result['num2']
print("After swap: num1 =", num1, "num2 =", num2)

Here, we have used swap_numbers() to return a dictionary with swapped values for num1 and num2. We can get the values by extracting them from the dictionary.

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

10. Using a Generator Function

Now, we will use generator function that returns the swapped values of a and b when iterated over.

We can use it as follows –

def swap_numbers(a, b):
    yield b
    yield a

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

Here, we get swapped values when swap_numbers() function is called. These values are stored in variables num1 and num2.

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

11. Using deque Data Structure

deque works in first come first out theory. We can use deque to swap two numbers in python with examples as shown below –

from collections import deque

def swap_numbers(a, b):
    queue = deque([b, a])
    return queue.popleft(), queue.popleft()

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

Here, we are using deque data structure from collection module. In this deque, we are storing swapped values of a and b. The values are then dequeued and assigned to num1 and num2.

Output:

Before swap: num1 = 5 num2 = 10
After swap: num1 = 10 num2 = 5

12. Using Single Line of Code with Arithmetic Operations

If we want to write single line code to swap two numbers in python with examples, we can do so using walrus operator as shown below –

def swap_numbers(a, b):
    return a + b - (b := a), a

# Example usage
num1 = 5
num2 = 10
print("Before swap: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swap: num1 =", num1, "num2 =", num2)

Output:

This program uses a single line of code with arithmetic operations and the walrus operator (:=) to swap the values of a and b.

That’s how we can swap two numbers in python with examples. Learn more about python at official documentation

Leave a Reply