-1

Just wondering what happens when I run

nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i] in python3.

I know it works when I do like x = nums[i] - 1 nums[i], nums[x] = nums[x], nums[i] But still don't know what exactly happened.

Charlie
  • 3
  • 1
  • You need to specify what you need to do. – Kshitij Joshi Oct 06 '21 at 05:48
  • Did you try it out? Does seem like a question you could figure out yourself with near to no effort. If you have no python installed, you can use an online interpreter such as https://www.programiz.com/python-programming/online-compiler/ – Christian Oct 06 '21 at 05:49

2 Answers2

0

Python rules are quite specific.

When evaluating a = b = c = ... = z, the right hand side is evaluated, and then this is assigned, in order to a then b, then c, ...

When assigning a value to a normal tuple, the value assigned must have the same length as the tuple being assigned to. The first value is assigned to the first part of the tuple, then the second value is assigned to the second part of the tuple, and so on.

Between these two rules, what happens in the above code is clear. These steps occur in order:

  1. The right hand side is evaluated.
  2. The first part of the resulting tuple is assigned to the first part of the left hand side
  3. The second part of the resulting tuple is assigned to the second part of the left hand side.
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
0
  • To Swap elements correctly use this
nums=[4,8,3,7,5]
print('before',nums)
i=3
nums[i], nums[i - 1] = nums[i - 1], nums[i]
print('after',nums)
before [4, 8, 3, 7, 5]
after [4, 8, 7, 3, 5]
  • To Know why your code doesn't work see the following code

the code will bec executed from the most right to left

nums=[4,8,7,3,5]
i=3

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

#first element
>nums[i] ----> 7
>nums[3] ----> 7
>nums=[4,8,7,7,5]

#second element
>nums[nums[i] - 1] ---> 3
>nums[nums[3] - 1] ---> 3 #nums[3] became 7 
>nums[7 - 1] ---> 3
>nums[6] ---> 3  #index out of range
Mahmoud Aly
  • 578
  • 3
  • 10