How do you assign values to two variables in Python?

There are several ways in Python to assign values to two variables.

  1. Direct assignment: Using the equal sign to assign the value of one variable to another variable.
a = 5
b = a
  1. Simultaneous assignment: use a comma to separate multiple variables and assign their values to the corresponding variables.
a, b = 5, 10
  1. Exchange values: Values of two variables can be exchanged to achieve assignment between variables.
a, b = b, a
  1. Extended assignment: performing operations on a variable before assigning it to itself.
a = 5
a += 2  # 等价于 a = a + 2

It is important to note that in Python, assignment is done by reference, which means multiple variables can refer to the same object.

bannerAds