There 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
def swap_variables_without_temp(a, b):
a = a + b
b = a - b
a = a - b
return a, b
a = 10
b = 20
print("Before swapping:")
print("a = ", a)
print("b = ", b)
a, b = swap_variables_without_temp(a, b)
print("After swapping:")
print("a = ", a)
print("b = ", b)
Method 2: Using bitwise XOR
Python
def swap_variables_without_temp_using_xor(a, b):
a = a ^ b
b = a ^ b
a = a ^ b
return a, b
a = 10
b = 20
print("Before swapping:")
print("a = ", a)
print("b = ", b)
a, b = swap_variables_without_temp_using_xor(a, b)
print("After swapping:")
print("a = ", a)
print("b = ", b)
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
There 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.