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.
source share