Разберитесь с свопингом в Python: почему a, b = b, a не всегда эквивалентно b, a = a, b?Python

Программы на Python
Гость
Разберитесь с свопингом в Python: почему a, b = b, a не всегда эквивалентно b, a = a, b?

Сообщение Гость »


Как мы все знаем, питонический способ поменять местами значения двух элементов and is

Код: Выделить всё

a, b = b, a
and it should be equivalent to

Код: Выделить всё

b, a = a, b
However, today when I was working on some code, I accidentally found that the following two swaps give different results:

Код: Выделить всё

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]
What is happening here? I thought in a Python swap the two assignments happen simultaneously and independently.

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

Вернуться в «Python»