Home Icon Home Resource Centre Swap Two Variables In Python- Different Ways | Codes + Explanation

Swap Two Variables In Python- Different Ways | Codes + Explanation

Swapping two variables in Python can be achieved using different methods in Python. Read the article below to understand every approach in detail with examples.
Shreeya Thakur
Schedule Icon 0 min read
Swap Two Variables In Python- Different Ways | Codes + Explanation
Schedule Icon 0 min read

Table of content: 

  • Swapping in Python
  • Swapping Two Variables Using A Temporary Variable
  • Swapping Two Variables Using The Comma Operator In Python
  • Swapping Two Variables Using The Arithmetic Operators (+,-)
  • Swapping Two Variables Using The Arithmetic Operators (*,/)
  • Swapping Two Variables Using The XOR(^) Operator
  • Swapping Two Variables Using Bitwise Addition and Subtraction
  • Swap Variables In A List
  • Conclusion
  • Frequently Asked Questions (FAQs)
expand

Variable swapping is a typical programming procedure that Python and other computer languages employ. The goal of this essay is to give readers a thorough understanding of the various Python variable-swapping methods. A temporary variable, arithmetic operators, the XOR operator, the comma operator, and bitwise addition and subtraction are a few of the techniques we will examine.

This article will walk you through each method step by step, regardless of your experience with Python development or your desire to improve your skills. Let's discover the ways to swap values of variables in Python.

Learn Python in 6 weeks! Check out this course on Unstop

Swapping in Python

Think about the case when the initial values of the two variables, a and b, are 5 and 10, respectively. The values of 'a' and 'b' should be swapped so that 'a' should be 10 and 'b' should be 5. This article will examine various methods for completing this swapping. These include swapping using a temporary variable, comma operator, arithmetic operators, etc. Each technique will be thoroughly described, giving the underlying idea a clear comprehension. Let's get started. 

Swapping in Python

Swapping Two Variables Using A Temporary Variable

The most common method of swapping in Python is by using a temporary variable. In this method, we create a third temporary variable and assign the value of the first original variable to it. And then carry on a series of other assignments as mentioned in the points below:

  • Say, the value of 'a' will be kept in a third variable that we'll refer to as a temporary variable.
  • Then, we shall assign the value of b to a.
  • Finally, we shall provide 'b' the temporary variable's value.
  • We can then carry out the swap using a temporary storage site. 

Code Example:

Output:

After swapping:
a = 10.0
b = 5.0

Explanation:

  1. First we created and declared two variables called a and b. Then, we assigned them values 5 and 10 respectively.
  2. Next, we create and declare a new variable called temp. This will be our temporary variable to help swap the values of a and b.
  3. Now we set temp equal to the value of a, which is 5.
  4. Then, we set its value equal to the value of b, which is 10.
  5. Now a's value is 10 instead of 5.
  6. Next, we set b's value equal to the value of temp, which is 5.
  7. So now b's value is 5 instead of 10.
  8. We swapped the values in a and b using the temporary variable temp.
  9. Finally, we print them to see the swapped values as output.

Swapping Two Variables Using The Comma Operator In Python

One way to swap two variables in Python using the comma operator is by assigning the values of the two variables to each other separated by a comma. This method does not require a third variable. We can use this operator for swapping in Python as follows:

  • Let's call the initial two variables 'a' and 'b', which contain their corresponding values.
  • We use the comma operator in a single line of code to switch the values of "a" and "b."
  • We can assign several values in a single statement using the comma operator.
  • The comma operator is used to concurrently assign the value of 'b' to 'a' and the value of 'a' to 'b'.
  • The values of 'a' and 'b' are switched in this way. 'a' now has 'b''s original value, and 'b' now has 'a''s original value.

As is evident, there is no need for a temporary variable or any further actions for this switch to be accomplished in a single line of code. Let’s take a look at a code example that shows an implementation of this method of swapping two variables in Python.

Code Example:

Output:

After swapping:
a = 10.0
b = 5.0

Explanation:

  1. First we created and declared two variables called a and b, and then assign them values 5 and 10 respectively.
  2. Now we get to the swapping part i.e., a, b = b, a

Let's break this down:

  1. On the left side, we have a and b, and on the right side, we have b and a.
  2. The values on the right side are assigned to the variables on the left side.
  3. So b (which is 10) gets assigned to a.
  4. And a (which is 5) gets assigned to b.
  5. The values have been swapped.
  6. Finally, we print them to see the swapped values as output.

Swapping Two Variables Using The Arithmetic Operators (+,-)

The arithmetic operator is one of the common techniques used in Python to swap variables, where we use various arithmetic operators in pairs to swap variables like (+,-) and (*,/). Let us discuss here how will we use (+,-) arithmetic pair to swap variables:

  • We shall change the values of "a" and "b" using addition and subtraction procedures.
  • The total of 'a' and 'b' will be updated by adding 'a' and 'b'.
  • Then, we will assign the difference to "b" by deducting it from the revised value of "a."
  • Finally, we will allocate the difference to 'a' by deducting the updated value of 'a' (which now holds the original value of 'b') from 'b'.
  • This technique employs mathematical processes to achieve the swap.

Code Example:

Output:

After swapping:
a = 10.0
b = 5.0

Explanation:

  1. First we created and declared two variables called a and b, and then assign them values 5 and 10 respectively.
  2. Now we do : a = a + b
  3. This takes the original value of a (which is 5) and adds b (which is 10) to it. So now a becomes 5 + 10 = 15
  4. Next we do : b = a - b so, b gets set to the current value of a (which is 15) minus the original value of b (which is 10). So b becomes 15 - 10 = 5.
  5. Finally we do : a = a - b, so a gets set to its current value (15) minus the current value of b (5). So a becomes 15 - 5 = 10.
  6. The values have been swapped.
  7. Finally we print them out to see the swapped values.

Swapping Two Variables Using The Arithmetic Operators (*,/)

The arithmetic operator is also one of the common techniques used in Python to swap variables, where we use various arithmetic operators in pairs to swap variables like (+,-) and (*,/).

Let us discuss here how will we use the (*,/) arithmetic pair to swap variables:

  • Get the variables started: Start by giving the two variables you want to swap their starting values. Suppose we have the variables 'a' and 'b'.
  • Multiply 'a' by 'b' to get the answer.
  • Give 'a' the outcome of the multiplication.
  • Subtract the modified value of 'a' from 'b's' initial value.
  • Assign 'b' the division's outcome.
  • Subtract the updated value of 'b' from the updated value of 'a'.
  • 'A' should be given the division's outcome.
  • The values of 'a' and 'b' will be switched by carrying out these actions. Now, the initial value of 'b' will be saved in 'a,' and the initial value of 'a' will be stored in 'b'.

Code Example:

Output:

After swapping:
a = 10.0
b = 5.0

Explanation:

  1. First, we created and declared two variables called a and b, and then assigned them values 5 and 10, respectively.
  2. Now we do : a = a * b
  3. This takes a (which is 5) and multiplies it by b (which is 10). So now a becomes 5 * 10 = 50.
  4. Next, we do: b = a / b, so b gets set to a (which is 50) divided by the original b (which is 10). So b becomes 50 / 10 = 5.
  5. Finally, we do: a = a / b, so a gets set to the current a (50) divided by the current b (5).
  6. So a becomes 50 / 5 = 10.
  7. The values have been swapped.
  8. Finally, we print out the swapped values.

Swapping Two Variables Using The XOR(^) Operator

Python allows you to swap two variables by using the bitwise XOR operator (). When comparing two operands, the XOR operator compares their corresponding bits and returns 1 if they differ and 0 if they are the same. Because of this, whenever the bits of the two variables differ, the outcome of an XOR operation on two variables will be a number with all of its bits set to 1.

For instance, when the digits 10 and 5 are XORed, the result is 11 (0b1010 ^ 0b0101 = 0b1111). This is because the result sets the bits that are different in the two numbers (1 and 0) to 1 while setting the same bits (0 and 0) to 0.

Let us now see how we can use this property of XOR operator to swap variables in Python :-

  • Assume that we wish to swap the values of the two variables "a" and "b."
  • Beginning with 'a,' assign 'b' the XOR operation between 'a' and 'b'. The value of 'a' and 'b' added together is temporarily stored thanks to this step.
  • Then, give the updated value of 'a' (which now contains the combined value) and the original value of 'b' in the XOR operation. By doing this, the value of 'a' is essentially subtracted from the combined value, leaving only the original value of 'b'.
  • Lastly, give 'a' the XOR operation between the updated values of 'a' and 'b'. By removing the original value of "b" from the combined value in this phase, the original value of "a" is obtained.
  • Thus, we successfully swapped 'a' and 'b'.

Code Example:

Output:

After swapping:
a = 10.0
b = 5.0

Explanation:

  1. First, we created and declared two variables called a and b, and then assigned them values 5 and 10, respectively.
  2. Then, we start the swapping process by doing : a = a ^ b.
  3. This takes a (which is 5) and does an XOR with b (which is 10).
  4. 5 XOR 10 equals 15, so now a becomes 15 (binary 1010 ^ 0101).
  5. Next, we do : b = a ^ b, so b gets set to a XOR b. a is 15 and b is 10.
  6. 15 XOR 10 equals 5, so b becomes 5 (binary 1010 ^ 1010).
  7. Consequently, b now equals 5
  8. Finally, we do : a = a ^ b, so a gets set to a (which is 15) XOR b (which is 5).
  9. 15 XOR 5 equals 10. So a becomes 10 (binary 1010 ^ 0101).
  10. The values have been swapped.
  11. Lastly, we print them out the swapped values.

Swapping Two Variables Using Bitwise Addition and Subtraction

Bitwise operators, as you might know, operate on individual bits of binary numbers. In this section, we will look at bitwise addition and subtraction techniques, though they aren’t commonly used.

  • Bitwise addition involves adding the matching bits of two binary numbers while accounting for carry values from earlier places. For example, the addition of 5 (101) and 3 (011) would result in 8 (1000) since 1+1 in the rightmost bit causes a carry of 1 to the following bit.
  • Bitwise subtraction includes taking into account borrowed values from earlier positions as you subtract the bits of one binary integer from another. For example, if 3 (011) were subtracted from 5 (101), the result would be 2 (010), where 1 is taken from the leftmost bit position.

We can use bitwise addition and subtraction for swapping in Python programs by taking advantage of the fact that the sum of two numbers is the same as the complements of those numbers' differences. Let us now see how we can use this operator to swap variables in Python:

  • Bitwise addition and subtraction operations between 'a' and 'b' allow us to accomplish the swap.
  • We will update 'a' with the outcome by adding 'a' and 'b' bitwise.
  • The difference will then be assigned to bitwise operand 'b' by deducting the initial value of 'b' from the revised value of 'a'.
  • We will finally allocate the difference to bitwise divide the new value of 'b' from 'a'.
  • This technique performs the swap using bitwise operations.

Code Example:

Output:

After swapping:
a = 10
b = 5

Explanation:

  1. First, we created and declared two variables called a and b, then assigned them values 5 and 10, respectively.
  2. Now we start the swapping process by doing : a = (a & b) + (a | b)
  3. (a & b) does a bitwise AND of 5 (a) and 10 (b), which is 0.
  4. (a | b) does a bitwise OR of 5 (a) and 10 (b), which is 15.
  5. So we are setting a to 0 + 15 = 15.
  6. Next, we do b = a + (~b) + 1, so a is 15, ~b flips the bits in 10 to get -11, and 1 is added.
  7. So b becomes 15 + (-11) + 1 = 5
  8. Finally, we do: a = a + (~b) + 1, so a is 15, ~b flips 5 bits to get -6, and 1 is added.
  9. So a becomes 15 + (-6) + 1 = 10
  10. The values have been swapped.
  11. Finally, we print them out the swapped values.

Swap Variables In A List

Swapping variables in a list involves rearranging the values or elements within the list. This can be achieved using the following steps:

  • We begin with a list of various items or values.
  • We use a special mechanism to swap the values in the list.
  • The indices of the two components that we want to swap are first determined.
  • Let's assume that 'i' and 'j' are the indices.
  • We set the value of element 'i' to a temporary variable before switching out the variables.
  • The value of element 'j' is then assigned to the position of element 'i'.
  • Finally, we place the temporary variable's value in the element 'j''s location.

Also Read: Difference between list and tuple in Python

Code Example:

Output:

After swapping:
my_list = [2, 1, 3, 4, 5]

Explanation:

  1. We begin by creating a list called my_list with the entries [1, 2, 3, 4, 5].
  2. Next, we create a variable called i and set it equal to 0 : i = 0. This will represent the index of the first value we want to swap.
  3. Then we create a variable called j and set it to 1 : j = 1. This will represent the index of the second value we want to swap.
  4. Now we get to the swapping : my_list[i], my_list[j] = my_list[j], my_list[i]
  5. This uses the comma operator to swap the values at index i and index j in my_list.
  6. So my_list[0] (which is 1) gets swapped with my_list[1] (which is 2).
  7. After this, my_list will contain values as : [2, 1, 3, 4, 5]. So, the values are swapped.
  8. Finally, we print out my_list to see the swapped values in the list.

Conclusion

Swapping variables is a common programming task that involves exchanging the values stored in two variables. There are several techniques to swap variables in Python, each with their own advantages.

The key methods covered include using a temporary third variable, the comma operator, arithmetic operators like multiplication and division, bitwise XOR and bitwise AND/OR operators, and swapping values in lists by index. All these approaches allow efficient swapping without loss of data. The optimal technique depends on the specific context and programmer's preferences. But having an understanding of these versatile mechanisms gives Python programmers flexibility in interchanging values as needed. Happy Coding !!

Frequently Asked Questions (FAQs)

Q1. How to swap two elements in a string in Python?

Strings in Python are immutable, which means that their values cannot be changed directly. As a result, direct element swapping within a string is not possible. However, by changing the string into a list, switching the entries in the list, and then changing the list back to a string, you can accomplish a similar result. Here is how to swap two elements in a string step-by-step:

  • Start with the string you wish to change.
  • Using the list() method, which divides each character into distinct list elements, turn the string into a list.
  • The indices of the two components you want to swap out should be determined.
  • To swap the elements at the specified indices, use standard list element switching procedures.
  • Convert the list back to a string using the join() function once the elements have been switched.
  • Use the join() function to concatenate the components of the list back into a single string by specifying an empty string as the separator.
  • The two elements will be switched in the final string.

Here is an instance to demonstrate the procedure:

Output:

Swapped string: Hlleo

The string "Hello" is where we begin in the aforementioned example. It is converted to a list, which is then changed to a string by switching the items at indices 1 and 3 ('e' and 'l'). "Hlelo" is the swapped string that results.

Remember that while using this method, you can swap items within a string without really changing the string itself. The desired elements are swapped into a new string that is then created.

Q2. How do you swap two lists in Python? Give an example.

You can use a temporary variable to hold one of the lists and then assign the data from one list to the other in Python to swap two lists. Here is an instance to demonstrate the procedure.

Code Example:

Output :

Swapped list1: [4, 5, 6]
Swapped list2: [1, 2, 3]

Q3. How to Swap three numbers in Python? Give an example.

To swap three numbers in Python, we can utilize the same technique used for swapping two numbers i.e. using a temporary variable. Here's an example of how we can do it :

Code Example:

Output:

Swapped values:
a = 2
b = 3
c = 1

Three variables, a, b, and c, hold the initial values in the example above. These are the actions we take to exchange these values:

  • Give a temporary variable called temp the value of a.
  • Give the value of b.
  • Give b the value of c.
  • Give c the value of temp, which contains a's initial value.
  • The values of a, b, and c have been rearranged as a result of the swap.

As a result, the values are switched, with a now holding b's original value, b's original value being held by c, and c's original value being held by a.

Q4. How to swap two numbers in Java using a temporary variable?

To swap two numbers in Java using a temporary variable is similar to Python, we can follow these steps:

  • Set the integers you want to swap into a temporary variable called temp with the same data type.
  • Give temp the value of a.
  • Give a b value and vice versa.
  • Give b the value of temp, which contains a's initial value.
  • The values of a and b have been switched after the swap.

Because of this, a now has b's original value and b now has a's original value. Let us see an example of this :

import java.io.*;

public class NumberSwapper {

public static void main(String[] args) {

// Original values

int a = 5;

int b = 10;

// Swapping two numbers using a temporary variable

int temp = a;

a = b;

b = temp;

// Print the swapped values

System.out.println("Swapped values:");

System.out.println("a = " + a);

System.out.println("b = " + b);

}

}

Output :

Swapped values:
a = 10
b = 5

Q5. What does swap() mean in Python?

In Python, swap() typically refers to exchanging the values of two variables. However, it's important to note that Python does not have a built-in swap() function like other programming languages. Instead, you can achieve swapping using various techniques like a temporary variable, tuple unpacking, etc.

Q6. How to swap two variables in a single line in a Python program?

One of the most concise ways to swap two variables in a single line of code is by utilizing the comma operator. We have discussed this method above in this article. Let us see one more example of it.

Code Example:

Output :

After swapping:
a = 11
b = 6

Q7. How to swap two strings without using a 3rd variable in Python?

As you may already be aware, Python has a built-in data type called a string that represents a group or stream of characters. We can use a variety of methods, including the comma operator, the temporary variable approach, and string concatenation with slicing, to swap two strings.

Combining string concatenation and slicing is one of the most widely used methods. While string slicing enables us to extract specific chunks of a string, string concatenation refers to the combining of two strings together. We can get the desired swapped version of the strings by combining these processes.

Code Example:

Output:

After swapping:
string1 = World
string2 = Hello

You may be interested in reading: 

  1. 12 Ways To Compare Strings In Python Explained (With Examples)
  2. Python IDLE | The Ultimate Beginner's Guide With Images & Codes!
  3. Python String.Replace() And 8 Other Ways Explained (+Examples)
  4. How To Reverse A String In Python? 10 Easy Ways With Examples!
Edited by
Shreeya Thakur
Sr. Associate Content Writer at Unstop

I am a biotechnologist-turned-content writer and try to add an element of science in my writings wherever possible. Apart from writing, I like to cook, read and travel.

Comments

Add comment
comment No comments added Add comment