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$
  • 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.

| cite | improve this answer | |
$\endgroup$

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