2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

a[None] is the same as a[None,:] and produces a (1,10) shaped view. As you say it's that view that's being changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.