Python synchronous assignment semantics

Consider the following Python 3 code:

a = [-1,-1,-1] i = 0 

Now consider the following two versions of simultaneous assignment for both a and i:

Purpose of version 1:

 a[i],i = i,i+1 

Purpose of version 2:

 i,a[i] = i+1,i 

I would expect these two versions of concurrent assignments to be semantically equivalent. However, if you check the values ​​of a and i after each of the simultaneous assignments, you will get different states:

Output for print(a,i) after assigning version 1:

 [0, -1, -1] 1 

Output for print(a,i) after assigning version 2:

 [-1, 0, -1] 1 

I'm not an expert on Python semantics, but this behavior seems weird. I would expect both assignments to behave like a version 1 assignment. Also, if you check the following link, you can expect both assignment versions to lead to the same state:

Google Book Excerpt Link

Is there something I miss in Python semantics for simultaneous jobs?

Note. This strange behavior does not seem to be reproducible, for example, when the variable a is of integer type; it seems that a should have a list of types (maybe this applies to any mutable type?).

+7
source share
1 answer

In this case:

 i, a[i] = i + 1, i 

The right-hand side evaluates the tuple (1, 0). Then this tuple is unpacked on i , and then a[i] . a[i] is evaluated during unpacking, and not earlier, therefore corresponds to a[1] .

Since the right side is evaluated before any unpacking occurs, the call to a[i] on the right side will always be a[0] regardless of the final value of i

Here is another useless fun example for you.

 >>> a = [0,0,0,0] >>> i, a[i], i, a[i] = range(4) >>> a [1, 0, 3, 0] 
+7
source

All Articles