How do I swap two variables in Python?
Short answer
Write a, b = b, a. Python builds a tuple of the right-hand values first, then unpacks it, so no temporary variable is needed.
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1#Why it works
The right-hand side is evaluated completely before any assignment happens. Python builds the tuple (b, a) — that is, (2, 1) — and only then unpacks it into the names on the left. The old value of a is still intact when b is read.
This is the same mechanism behind:
first, second, third = [1, 2, 3]
head, *tail = [1, 2, 3, 4] # head=1, tail=[2,3,4]
first, *middle, last = [1,2,3,4] # middle=[2,3]#Swapping list elements
items[i], items[j] = items[j], items[i]This is the swap inside every sorting algorithm, and it is why Python implementations of bubble sort read so much more clearly than C ones.
#The one place it does not apply
If the two sides share an index that is itself being reassigned, evaluation order can surprise you:
i = 0
items = [1, 2, 3]
i, items[i] = 1, 99 # items[1] = 99, not items[0]Targets are assigned left to right, so i becomes 1 before items[i] is resolved. Rare, but worth knowing it exists.