+= Operator on list of indices - unexpected behaviour
See original GitHub issueHi, I stumbled upon an interesting and unexpected (to me) behaviour when using the +=
operator on a np.ndarray
:
import numpy as np
a = np.zeros(3)
indices = [0, 0, 1, 1, 2]
a[indices] += 1
The thing is, knowing that +=
avoids creating copies and that slicing also creates views and not copies, I would expect this to add 2 to a[0]
, 2 to a[1]
and 1 to a[2]
. Instead I witness the following:
>>> a
array([1., 1., 1.])
Is this a bug? If not, can you please explain this?
Thanks, Michael
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:10 (6 by maintainers)
Top Results From Across the Web
Unexpected behavior using the << operator into a specific index in ...
When you are doing stack = [6,7] result = stack << 9. You are actually appending the element 9 to the array stack...
Read more >Unexpected behaviour from the 'in' operator - python-list@python.org
I have just noticed that the 'in' operator for lists appears to ... only if there exists an index i such that x...
Read more >List Index Out of Range – Python Error Message Solved
Using an index number that is out of the range of the list. You'll get the Indexerror: list index out of range error...
Read more >11. Lists — How to Think Like a Computer Scientist
It is common to use a loop variable as a list index. ... Although this behavior can be useful, it is sometimes unexpected...
Read more >Errors and exceptions - Object-Oriented Programming in Python
This is likely to cause some odd and unexpected behaviour. ... possible IndexError , which could occur if the index provided exceeds the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Numpy overloads
c += b
in a way that uses less memory thatc = c + b
, but python provides no way to overload the combined indexing and augmented assignment.Well in this case it is relevant, since the indices are unique and they basically produce the same result.