[Numpy-discussion] curious behavior with indexed assignment

Nathaniel Smith njs@pobox....
Wed Aug 25 20:16:55 CDT 2010


So on IRC #scipy just now, Carlos Scheidegger pointed out some
behavior that I at least find very surprising:

>>> a = np.zeros(10)
>>> a[:] = np.arange(3)
ValueError: shape mismatch: objects cannot be broadcast to a single shape

Okay, that's what we expected. But if we use explicit indices...

>>> a[np.arange(10)] = np.arange(3)
>>> a
array([ 0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.,  0.])

Also works with boolean masks:

>>> a = np.zeros(10)
>>> a[np.ones(10, dtype=bool)] = np.arange(3)
>>> a
array([ 0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.,  0.])

And if the array being assigned is too short, then the rvalue gets
silently truncated:

>>> a = np.zeros(10)
>>> a[np.arange(5)] = np.arange(10)
>>> a
array([ 0.,  1.,  2.,  3.,  4.,  0.,  0.,  0.,  0.,  0.])

Shouldn't these all give errors? This "recycling rule" behavior (as R
would call it) seems totally inconsistent with usual broadcasting
rules, but I can't seem to find any documentation or anything on it.
(And indeed, I tried reproducing it with 1-d slices of a 2-d array,
and just got "array is not broadcastable to the correct shape"
exceptions.)

Is this a bug or intentional?

(Tested with self-build Numpy 1.4.1 on Python 2.6.5.)

-- Nathaniel


More information about the NumPy-Discussion mailing list