1

So, I know that you can do this by doing

>>> arr[mask] = value

However, if I want to make the code shorter (and not recompute the mask and index each time), I'd like to do something like this:

>>> sub = arr[mask]
>>> sub[...] = value # This works in other cases, but not this one.

My understanding is that doing Ellipses indexing should allow you to specify that you're not reassigning a given variable, but are rather broadcasting to the actual array.

So, here's the question: why doesn't it work?

My thinking is that it's related to the fact that:

>>> arr[mask] is arr[mask]
False

But surely since the mask indexed versions are just views (not copies of the underlying structure), this shouldn't break assignment.

4
  • Maybe...because sub is a value, it can be change to everything. So sub = arr[mask] will change sub to arr[mask](now, sub is a string). But sub = value will change sub to value(sub also is a string), it wouldn't change arr[mask] to value? Commented Oct 3, 2015 at 10:59
  • 2
    Seems very close if not a duplicate - stackoverflow.com/q/32739828/3293881 Commented Oct 3, 2015 at 11:13
  • 1
    @KevinGuan If you read my question properly, I didn't write sub = arr[mask], I wrote sub[...] = arr[mask] which forces the modification of sub. Commented Oct 3, 2015 at 12:50
  • @cyphar Oops, I didn't pay attention on it. Sorry about that :P Commented Oct 3, 2015 at 12:52

2 Answers 2

2

But surely since the mask indexed versions are just views (not copies of the underlying structure), this shouldn't break assignment.

The reason why this doesn't work is that indexing with masks will create a copy, not a view:

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).

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

Comments

2

arr[mask] is a copy. arr[mask]=... looks the same, but actually is a different assignment operation. Elsewhere I've explained this in terms of calls to __getitem__ and __setitem__.

Comments

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.