Why does np.array[None] update all values in that numpy arrray?

Viewed 20

I found a bug in my code and while fixing that bug, and I noticed a peculiar behavior in numpy.

a = np.arange(10) # ints 0 -> 9
a[None] = 20

print(a) # output --> [20, 20, 20, 20, 20, 20, ... 20]

Why do the values in every position get replaced with 20?

1 Answers

This is the expected behavior, not a bug. a[None] is not slicing/indexing but broadcasting. What it does does is to provide a different view of the underlying data of a.

And since you are modifying this view with a[None]=20, you also modify a's data, and therefore a itself.

Related