Swapping variable values in a single statement

Python allows you to assign more than one variable at a time when the left side of the assignment is a sequence as demonstrated in the code below.

>>>i, j =  [1, 2]
>>>print(i)
1
>>>print(j)
2

To swap values between i and j is a matter of reversing the sequence order and assigning it to the original sequence. This allows us to swap the values of two variables in a single statement.

>>>i, j = j, i
>>>print(a)
2
>>>print(b)
1

Leave a Reply

Close Menu