Home > Blockchain >  Why not call a reference when swapping elements using simultaneous assignment?
Why not call a reference when swapping elements using simultaneous assignment?

Time:12-18

I have a question regarding swapping elements in python, for which i couldn't find an answer on the net. What is the difference between the both alternatives that I tried and why does only the second one give the expected output? I worked on a selection sort algorithm and thus had to swap elements of a list. I had assigned the value of max(my_list) to the variable max_item.

(1) This was my first try swapping max_item and my_list[-1]:

max_item, my_list[-1] = my_list[-1], max_item

The actual output was:

[value of max_item, value of max_item]

(2) Then I tried the following:

my_list[my_list.index(max_item)], my_list[-1] = my_list[-1], my_list[my_list.index(max_item)]

This gave the expected output:

[value of my_list[-1], value of max_item]

Any advice is greatly appreciated. Thanks in advance!

CodePudding user response:

max_item has nothing to do with my_list, even if you do:

max_item = max(my_list)

The index in my_list that contains the maximal item and max_item are both aliases binding to the same underlying object, but when you reassign max_item (as opposed to mutating it in place, e.g. with a mutating method call, or reassigning one of its attributes), you rebind that name, breaking the aliasing, changing nothing in my_list.

Your second line of code works because you rebind the appropriate index in my_list. You only need to look it up for the reassignment though, so you could speed your code up and simplify a bit by using:

my_list[my_list.index(max_item)], my_list[-1] = my_list[-1], max_item
  • Related