How to swap the values of two variables without using a temporary variable in Python?
How to swap the values of two variables without using a temporary variable in Python?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
05-Jul-2023There are a few ways to swap the values of two variables without using a temporary variable in Python. Here are two methods:
Method 1: Using arithmetic operators
Python
Method 2: Using bitwise XOR
Python
Both methods work by using the fact that the XOR operator returns 1 when the two operands are different, and 0 when the two operands are the same. In the first method, the values of a and b are added together, and then subtracted from each other. This effectively swaps the values of a and b. In the second method, the values of a and b are XORed together, and then XORed again. This also effectively swaps the values of a and b.
Which method you use to swap the values of two variables without using a temporary variable depends on your specific needs. If you need to swap the values of two variables that are of different data types, then the first method is a good option. If you need to swap the values of two variables that are of the same data type, then the second method is a good option.