SoFunction
Updated on 2025-03-05

Four ways to implement numerical exchange in Python

Use temporary variables

This method is the easiest and easiest to understand, and is suitable for all programming languages. The implementation process is as follows:

tmp = a
a = b
b = tmp

Using tuple tuple

This method is a unique method in Python and can be implemented only with one line of code. It uses tuples, and its general principle is as follows:

  • b, a on the right form a tuple composed of b and a
  • Unpack the tuple and assign values ​​to the a and b on the left respectively
a, b = b, a

We can also use the help of a list and place a list composed of b and a on the right, but note that you cannot place a collection on the right, because the collection is unordered, which will lead to the wrong final exchange result.

a, b, c, d = 100, 200, 3000, 400

# Tuple on the right# a, b, c, d = d, c, b, a
# print(a, b, c, d)  # 400 3000 200 100

# The right is the list# a, b, c, d = [d, c, b, a]
# print(a, b, c, d)  # 400 3000 200 100

# The set on the right will cause the final exchange value to be incorrecta, b, c, d = {d, c, b, a}
print(a, b, c, d)  # 400 100 3000 200

Use addition and subtraction or multiplication and division

Whether using addition and subtraction or multiplication and division, temporary variables are not required. The implementation process is as follows:

# Addition and subtractiona = a + b
b = a - b  # b = (a + b) - b = a
a = a - b  # a = (a + b) - b = (a + b) - a = b 
#No one answers the questions encountered during study?  The editor has created a Python learning exchange group: 531509025
# Multiplication and divisiona = a * b
b = a // b  # b = (a * b) // b = a
a = a // b  # a = (a * b) // b = (a * b) // a = b 

Use XOR operation

Characteristics of XOR operation: 0 XOR or any number a, the result is a; any number a XOR itself, that is, a XOR a, the result is 0. At the same time, the XOR operation satisfies the exchange law.

Using XOR operation does not require the use of temporary variables. The implementation process is as follows:

a = a ^ b
b = a ^ b  # b = (a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a
a = a ^ b  # a = (a ^ b) ^ b = (a ^ b) ^ a = (a ^ a) ^ b = 0 ^ b = b

This is the end of this article about four ways to implement numerical exchange in Python. For more related Python numerical exchange content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!