In this article, we will learn about how to write python program to swap two complex numbers without using third variable.

## Getting Started

The task is to swap two complex numbers in python without using third variable.

For example,

Assume **a = 50.1 + 30j** and **b = 60.3 – 20j**, then output should be **a = 60.3 – 20j** and **b = 50.1 + 30j**

Now, we need to write python program to swap two complex numbers without using third variable.

There are multiple ways to achieve above tasks.

## 1. Using Tuple Packing and Unpacking

This is simplest way to swap complex numbers without using third variable. Here, we use tuple packing and unpacking technique.

It can be done as shown below –

# Define two complex numbers a = 50.1 + 30j b = 60.3 - 20j print("Before swap: a =", a, "b =", b) # Perform the swap using tuple unpacking a, b = b, a print("After swap: a =", a, "b =", b)

Here,

- Statement
**a, b = b, a**does the actual swapping process.

Output:

Before swap: a = (50.1+30j) b = (60.3-20j) After swap: a = (60.3-20j) b = (50.1+30j)

## 2. Using Multiplication and Division Operation

We can also use multiplication and division operation too. This is similar to what we have seen in above program. Using multiplication and division operation, below is the sample python program to swap two complex numbers without third variable.

It can be shown as below –

# Take input for complex numbers a_input = input("Enter the complex number for a (e.g., 3+2j): ") a = complex(a_input) b_input = input("Enter the complex number for b (e.g., 1-5j): ") b = complex(b_input) # Print the values before swapping print("Before swapping:") print("Value of a:", a, "and b:", b) # Swapping without using a third variable a = a * b # Multiply a by b. Then, assign the result to a b = a / b # Divide a (i.e now, it is a*b) by b. Then, assign the result to b a = a / b # Divide a by b. Then, assign the result to a # Print the values after swapping print("After swapping:") print("Value of a:", a, "and b:", b)

Output:

Enter the complex number for a (e.g., 3+2j): 4+2j Enter the complex number for b (e.g., 1-5j): 5+6j Before swapping: Value of a: (4+2j) and b: (5+6j) After swapping: Value of a: (5+6j) and b: (4+2j)

We have also covered many other ways to swap two complex numbers in python. You can have a look at them if you want. Learn more about python at official site.