I know that tuple assignment in Python such as the following
a, b = b, a
works by first packing b
and a
into a tuple (b, a)
and then unpacking it to a
and b
, so as to achieve swapping two names in one statement. But I found that if a
and b
are replaced by sliced Numpy arrays:
# intended to swap the two halves of a Numpy array
>>> import numpy as np
>>> a = np.random.randn(4)
>>> a
array([-0.58566624, 1.42857044, 0.53284964, -0.67801528])
>>> a[:2], a[2:] = a[2:], a[:2]
>>> a
array([ 0.53284964, -0.67801528, 0.53284964, -0.67801528])
My guess is that the packed tuple (a[2:], a[:2])
is actually a tuple of "pointers" to the memory location of a[2]
and a[0]
. When unpacking, first a[:2]
is overwritten by values starting from the memory at a[2]
. Then a[2:]
is overwritten by values starting from a[0]
. Is this the correct understanding of the mechanism?