Normally, if you attempt to assign past the end of an array in numpy, the non-existent elements are disregarded.
>>> x = np.zeros(5)
>>> x[3:6] = np.arange(5)[2:5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (3) into shape (2)
However, the same operation entirely past the end of the array "succeeds" if only one element is assigned:
>>> x[5:] = np.arange(5)[4:]
>>> x[5:] = np.arange(5)[4:100]
This only works if the RHS has one element:
>>> x[5:] = np.arange(5)[3:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (2) into shape (0)
Why is this the case? How is it possible not to get an error here? Is this behavior documented, or is it a bug?
In keeping with Python list behavior, you can slice off-the-end. The first case shows that's true for both the LHS and RHS.
The rest is broadcasting. 3 can't got into 2. 2 can't go into 0. But 1 can go into anything, including 0. We tend to think of broadcasting replicating a size 1 dimension to something larger, but replicating to 0 also works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With