Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Swap the Values of Two Variables

Python Swap the Values of Two Variables

Document Object Reference Manual Python3 Examples

In Python, swapping the values of two variables can be done in several ways. The most common is to use a temporary variable to hold one of the values and then swap them. In addition, Python offers a more concise way: swapping values using tuple unpacking.

Method 1: use a temporary variable

Example

a

=

5

b

=

10

Swap using a temporary variable

temp

=

a

a

=

b

b

=

temp

print

(

"Value of a after swapping:"

,

a

)

print

(

"Value of b after swapping:"

,

b

)

Code analysis:

Output result:

交换后 a 的值: 10
交换后 b 的值: 5

Method 2: use tuple unpacking

The code:

Example

a

=

5

b

=

10

Swap using tuple unpacking

a

,

b

=

b

,

a

print

(

"Value of a after swapping:"

,

a

)

print

(

"Value of b after swapping:"

,

b

)

Code analysis:

Output result:

交换后 a 的值: 10
交换后 b 的值: 5

Both methods can swap the values of two variables effectively, but tuple unpacking is more concise and Pythonic.

Document Object Reference Manual Python3 Examples