Python list element swap not working as expected

Viewed 376

I wrote a simple code two swap two items in a list, using the very basic:

a, b = b, a

the code looks like this:

nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]

the above swap results in an infinite loop where the items are duplicated in the list thus failing to swap. But modifying it to the following works:

nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]

Is the swap not working because of the order of the variables for swapping.

If so, how is it logical? What am I missing?

2 Answers
def swap(index1, index2, list_):
    a, b = list_[index1], list_[index2]
    list_[index1], list_[index2] = b, a
    return list_

could use a function such as this where you pass in the list and the list index of the items you want to swap and then it returns the list with the items swapped. there may be shorter solutions to this but it is definitely one way of doing things

index = nums[i]-1
nums[i],nums[index]=nums[index],nums[i]

This might fix the error

Related