To swap the contents of two variables, we usually use an additional variable as a temporary shelter for the value we will swap.
# python program for swapping variables
a = 10
b = 5
# create temporary variable
temp = a
a = b
b = temp
print('nilai a setelah ditukar ', a)
print('nilai b setelah ditukar ', b)
Output :nilai a setelah ditukar 5nilai b setelah ditukar 10
With the python programming language we can make it simple in a fast way without the need to define temporary variables.
# variable swap without defining a temporary variable
x = 10
y = 5
x, y = y, x
print('Nilai x setelah ditukarkan : ', x)
print('Nilai y psetelah ditukarkan : ', y)Output : Nilai x setelah ditukarkan : 5
Nilai y psetelah ditukarkan : 10 Process finished with exit code 0
As seen above that’s one of the conveniences in using the python programming language, we only use the multi-assignment syntax
x, y = y, x