Moving items in lists in python

I have a list, and I need to swap the first item in the list with the maximum item in the list.

But why does code 1 work, but code 2 does not work:

code 1:

a = list.index(max(list)) list[0], list[a] = list[a], list[0] 

code 2:

 list[0], list[list.index(max(list))] = list[list.index(max(list))], list[0] 

I thought Python would first evaluate the right side before assigning it to the names on the left?

+4
source share
1 answer

Python saves the results for several purposes from left to right, executing the destination target expression in that order.

So, your second version essentially boils down to the following:

 temp = list[list.index(max(list))],list[0] list[0] = temp[0] list[list.index(max(list))] = temp[1] 

Note that list.index(max(list)) is executed after changing list[0] and where you just saved the maximum value.

This is confirmed by the "Assignment of Applications" documentation:

  • If the target list is a list of goals, separated by commas: the object must be iterable with the same number of elements as in the target list, and elements are assigned from left to right , to the corresponding goals.

From there, it is as if each goal was the only goal, so the following documentation applies from left to right for each goal:

The purpose of an object for one goal is recursively determined as follows.

[...]

  • If the target is a subscription: evaluates the main expression in the link. It should give either a mutable sequence object (for example, a list) or a matching object (for example, a dictionary). Then the index expression is evaluated.

If you change the order of assignments, your code will work:

 list[list.index(max(list))], list[0] = list[0], list[list.index(max(list))] 

because now list[list.index(max(list))] is assigned first.

+5
source

All Articles