1
$\begingroup$

I learned that in numpy, given a vector, slicing and indexing could give different results. I ran the following codes:

a = np.array([1, 2])
b = np.array([3, 4, 5])
print(b[a])
c = b[1:]
print(b)
c[0] = 1
print(b)
print(c)
print(b[1:] is c)

and get the result:

[4 5]
[3 4 5]
[3 1 5]
[1 5]
False

Since when I modify c, b is also changed, that means I should have a True in the last line right? Why it is not the case?

Thank you for any help!

$\endgroup$

closed as off-topic by Evil, Discrete lizard, Yuval Filmus, chi, David Richerby Jul 18 '18 at 13:43

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – Discrete lizard, Yuval Filmus, chi, David Richerby
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    $\begingroup$ Programming questions are off-topic here. $\endgroup$ – Yuval Filmus Jul 17 '18 at 21:52
1
$\begingroup$

When you slice a Numpy array, you get a special "slice" object, which holds pointers back into the array it was taken from. So if you do the same slicing operation twice, you'll get two different slice objects, which contain pointers to the same array in memory. (If you compare them using == instead of is, you'll see they compare equal, even though they're different objects.)

You can get the same effect with memoryviews, which are in the standard library. Each memoryview is its own object with its own address, but many memoryviews can point into the same data structure.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.