Show the idiomatic tuple-unpacking swap in Python, and how to swap two elements of a list by index.
Python can swap two names in a single statement, because the whole right-hand side is worked out before any name on the left is bound again.
a, b = 1, 2
a, b = b, a
print(a, b) # 2 and 1
# The same trick works with any two values.
x, y = 'hello', 'world'
x, y = y, x
print(x, y) # world and hello
# It also works with list items addressed by index.
items = ['a', 'b', 'c']
items[0], items[2] = items[2], items[0]
print(items) # ['c', 'b', 'a']
The mechanism is a tuple on the right-hand side and a tuple pattern on the left. The interpreter builds the tuple (2, 1) and then unpacks it into the two names, so a ends up with the old value of b and b ends up with the old value of a. Because the swap is one single statement, there is never a moment in the middle where both names hold the same value.
The version that uses indexes follows the same rule with subscript targets instead of plain names. Python reads both right-hand subscripts from the original list before it performs either assignment, and that is why the swap comes out correct instead of overwriting items[0] before it has been read.
Two variations are worth knowing. The starred form lets you swap one variable against the rest of a sequence, so first, *rest = items takes the head of the list and leaves the remainder in rest, while head, *tail = items does the opposite. And for reversing a whole list, a, b = b, a is the manual version, while items.reverse() and items[::-1] are the built-in ones.