Search code examples
pythonswap

Why inline swapping returns unexpected result?


I am trying to swap two objects in python like this A[i], A[A[i] - 1] = A[A[i] - 1], A[i] is not giving me the correct output

According to the order of operation: https://docs.python.org/3/reference/expressions.html#evaluation-order the right hand side is resolved first and then do the assignment from left to right. Suppose i = 1 then we get A[1], A[3] = A[3], A[1]

Suppose A = [-1, 4, 3, 1] and i = 1 where i is an index

A[i], A[A[i] - 1] = A[A[i] - 1], A[i] 

I get [4,1,3,1] as the result even though I expected to get [-1, 1,3,4] i.e. A[1], A[3] = A[3], A[1]

But when I do this I get the correct [-1,1,3,4]. Why does this one work and the above does not?

A[A[i] - 1], A[i] = A[i], A[A[i] - 1]

Solution

  • When trying to assign A[A[i] - 1], A[i] has already changed.

    Let's break it down with i = 1:

    First, the right hand side expressions are evaluated:

    • At this point A[i] = A[1] = 4
    • So A[A[i]-1] = A[4-1] = A[3] = 1

    Now the assignments from left to right:

    • A[i] = A[1] <- 1
    • A[A[i]-1] = A[1-1] = A[0] <- 4
    • final result: [4, 1, 3, 1]