Strange built-in job

I struggle with this strange behavior in Python (2 and 3):

>>> a = [1, 2] >>> a[a.index(1)], a[a.index(2)] = 2, 1 

This leads to:

 >>> a [1, 2] 

But if you write

 >>> a = [1, 2] >>> a[a.index(1)], a[a.index(2)] = x, y 

where x, y != 2, 1 (maybe 1, 1 , 2, 2 , 3, 5 , etc.), this leads to:

 >>> a == [x, y] True 

As expected. Why a[a.index(1)], a[a.index(2)] = 2, 1 does not give the result a == [2, 1] ?

 >>> a == [2, 1] False 
+5
source share
1 answer

Because it is really interpreted as follows:

 >>> a = [1, 2] >>> a [1, 2] >>> a[a.index(1)] = 2 >>> a [2, 2] >>> a[a.index(2)] = 1 >>> a [1, 2] 

To quote, in accordance with the standard rules of appointment (highlighted by me):

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

The assignment of a[a.index(1)] (that is, a[0] ) occurs before the second task requests a.index(2) , by which time a.index(2) == 0 .

You will see the same behavior for any destination:

 foo = [a, b] foo[foo.index(a)], foo[foo.index(b)] = x, y 

where x == b (in this case, any assignment, where the first value on the right-hand side is 2 ).

+10
source

Source: https://habr.com/ru/post/1235122/


All Articles