+ 2
Python challenge question
I got this on a challenge and for the life of me I don't get it. arr = [4, 3, 1, 2] arr[0], arr[arr[0]-1] = arr[arr[0]-1], arr[0] print(arr) That prints [2, 4, 1, 2] I don't understand how this works. arr[0] is 4 right? And arr[arr[0]-1] is 2? So to me this look's like it should print [2, 3, 1, 4] Could someone help me understand this?
3 Answers
+ 4
In an expression like this, the right side of = is evaluated first and stored. So this is (2, 4).
Then the left side is executed from left to right.
So the left side actually reads:
arr[0], arr[2-1]
^
set to 2 first
+ 4
If it was written like this:
arr = [4, 3, 1, 2]
a = arr[0]
arr[0], arr[a-1] = arr[arr[0]-1], arr[0]
print(arr)
Then the output would be like you said. But it works in a different way when you put arr[arr[0]-1], because it's like calling the index 0 again, which now became 2, so it is like writing arr[2-1], which is 3, and that is why arr[1] get replaced instead of arr[3].
+ 3
Thanks for the help. I get it now. I was trying to go from left to right..