Simultaneous assignment semantics in Python

In this case:

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

The righthand side evaluates to a tuple (1, 0). This tuple is then unpacked to i and then a[i]. a[i] is evaluated during the unpacking, not before, so corresponds to a[1].

Since the righthand side is evaluated before any unpacking takes place, referring to a[i] on the righthand side would always be a[0] regardless of the final value of i

Here is another useless fun example for you to work out

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

Leave a Comment