0

Having a numpy array like x and a slice that includes all its elements as z, why the identity operators gives false, despite the fact that changing the value of any element in z reflects on x and vice versa

x = np.array([1, 2, 3, 4, 5])

z = x[:]

x is z 

# Output:
False
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Osama Hamdy
  • 103
  • 2
  • 9

1 Answers1

1

From Numpy Internals:

NumPy arrays consist of two major components, the raw array data (from now on, referred to as the data buffer), and the information about the raw array data.

in the case of slicing z = x[:], it is a view, NumPy stores the significant set of data that describes how to interpret the data in the data buffer at the different memory location but it can share elements from z, hence both have different id and hence False.

>>> x = np.array([1, 2, 3, 4, 5])
>>> z = x[:] # same as x.view()
>>> x[2]
3
>>> x[2] = 1
>>> x
array([1, 2, 1, 4, 5])
>>> z
array([1, 2, 1, 4, 5])
>>> x is z
False

If you modify x, z will be also modified. More reference at Numpy Documentation

hack3r-0m
  • 700
  • 6
  • 20
  • No, `z` is not a copy of `x`, it's a view of `x`. There is no copying going on. – MattDMo Dec 12 '20 at 20:54
  • by copy, I mean it has the same elements/values as `x`(due to `:`) – hack3r-0m Dec 12 '20 at 20:55
  • Important note... just kidding – adir abargil Dec 12 '20 at 20:56
  • You're still incorrect. Numpy is different from Python lists. There is only one array - `x`. `z` is a *slice* or a *view* into that array. It's like looking at an object through a window. Creating the same elements in a different memory location is called *copying*. – MattDMo Dec 12 '20 at 20:58