1

I need to swap elements in a Python list. It works when I'm using a temporary variable to handle the swapping but doesn't seem to work when I do the same thing in a pythonic style, i.e. a, b = b, a.

Suppose the index we are dealing with is i = 1. I am trying to swap the elements at A[i] and A[A[i]].

Input A = [2,3,4,5,6,7,8,9] Expected Output = [2,5,4,3,6,7,8,9]

First I tried the pythonic way. Didn't get the expected output.

>>> i = 1
>>> A = [2,3,4,5,6,7,8,9]
>>> A[i], A[A[i]] = A[A[i]], A[i]
>>> A
[2, 5, 4, 5, 6, 3, 8, 9]

The non-pythonic way worked.

>>> i = 1
>>> B = [2,3,4,5,6,7,8,9]
>>> temp = B[B[i]]
>>> B[B[i]] = B[i]
>>> B[i] = temp
>>> B
[2, 5, 4, 3, 6, 7, 8, 9]

I just want to know why this is and when I should avoid using simultaneous assignment.

Neeraj
  • 11
  • 1
  • 1
    Possible duplicate of [How to switch position of two items in a Python list?](https://stackoverflow.com/questions/2493920/how-to-switch-position-of-two-items-in-a-python-list) – FObersteiner Jul 24 '19 at 11:20

2 Answers2

1

It's because the code is assigning during the process not after, so if you do the reverse order:

A[A[i]], A[i] = A[i], A[A[i]]

The 3rd element will be fixed, but the 5th element will go wrong.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

When A[i] = A[A[i]] is executed, it means 3 (wiz. on 1 pos) is now 5 then, A[A[i]] = A[i], remember, here A[i] on LHS is already 5 and on index 5 it is 7, also hence index 3 is untouched.

changing the code a bit like stated in the above answer,

A[A[i]], A[i] = A[i], A[A[i]]

will do the thing where the indexes are kinda preserved.

P.hunter
  • 1,345
  • 2
  • 21
  • 45