Как мы все знаем, питонический способ поменять местами значения двух элементов
Код: Выделить всё
a
Код: Выделить всё
b
Код: Выделить всё
a, b = b, a
Код: Выделить всё
b, a = a, b
Код: Выделить всё
nums = [1, 2, 4, 3]
i = 2
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
print(nums)
# [1, 2, 4, 3]
nums = [1, 2, 4, 3]
i = 2
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
print(nums)
# [1, 2, 3, 4]
See also Multiple assignment and evaluation order in Python regarding the basic semantics of this kind of assignment.
See also Multiple assignment semantics regarding the effect and purpose of parentheses on the left-hand side of a multiple assignment.
Источник: https://stackoverflow.com/questions/681 ... t-to-b-a-a