0

Let's say I want to swap 2 elements in a list by their indexes (it's a snippet from an algorithm problem so looks a little tricky).

>>> nums = [4, 3, 2, 1]
>>> i = 1
>>> nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
>>> nums
[4, 3, 2, 1]

So it doesn't work.
While a swap using constant numbers work as expected.

>>> nums[1], nums[2] = nums[2], nums[1]
>>> nums
[4, 2, 3, 1]

Can anyone help me understand what happens in the line nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]? What's the evaluation/execution order or if I missed anything?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Nifall
  • 13
  • 3
  • 2
    The assignment to `nums[i]` happens _before_ the assignment to `nums[nums[i] - 1]`, so you briefly get `[4, 2, 2, 1]` then reassign 3 back to `nums[nums[i] - 1]` -> `nums[2 - 1]` -> `nums[1]`. – jonrsharpe Aug 16 '22 at 11:27
  • 1
    @jonrsharpe That's clear, thank you! – Nifall Aug 16 '22 at 11:38

0 Answers0