2

The example below is odd to me. Arrays a and c are different, but at modification of the first element of a, the first element of c changes as well. Why is the numpy array implemented like this? If a is assigned as a list, changing the first element of a does not change the first element of c. I cannot think of any example where the behavior of the numpy array would be desired.

import numpy as np

a = np.arange(3,5)
#a = [3, 4]
b = a
c = a[:]
d = a.copy()

print(a is b) # True
print(a is c) # False
print(a is d) # False

print(a, b, c, d) #[3 4] [3 4] [3 4] [3 4]

a[0] = -11.

print(a, b, c, d) #[-11   4] [-11   4] [-11   4] [3 4] HUH?!
1
  • a[:] is different for lists and arrays; the __getitem__ indexing methods are different. Commented Dec 18, 2016 at 20:55

1 Answer 1

3

Simple Numpy slices return a view, not a copy. As the name implies, a view is backed by the same data, just represented differently. This is part of what makes Numpy so fast, because it doesn't have to create copies of the data every time you slice.

See the docs.

I can't think of a reason why c=a[:] would be useful, but c=a[::2] might be useful. Let's say i get the average of every other element, then increase those by that average.

a=np.random.random(10)
b=a[::2]
b+=b.mean()
print a

There's just no reason to special-case your example to return a copy instead of a view. In fact, it would be quite counter-intuitive to people familiar with how Numpy slices work.

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

6 Comments

Can you come up with an example where a c = a[:] type of assignment is desired?
@Chiel One would be where you might want to change all elems to something : a[:] = something. Putting in that form, it would be c = something after you have c = a[:].
@Divakar That is the reverse example.
@Chiel No. Assigning to a complete slice of the array just seems pointless. But for returning views in general, yes, i added a simple example.
@Chiel: row = data[0,:]; if something: row[:] = 1; else: row[0] = 10 . Allows you to split indexing and assignment across multiple lines
|

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.