# Cave of Python

»»» Views vs. Copies in Numpy

## Views vs. Copies in Numpy

When you use basic indexing to obtain a slice of a Numpy array, a view is returned. This means you can use the returned slice to modify the original array.

To replace the slice you can use either another array of the same size, or a single number. In the latter case, Numpy broadcasts the number over the slice.

``````import numpy as np

values = np.random.randint(7,10, size=10)
print(values)

values[2:5] = 0
print(values)

values[2:5] = [1, 2, 3]
print(values)``````
``````[7 8 8 7 9 8 8 8 9 7]
[7 8 0 0 0 8 8 8 9 7]
[7 8 1 2 3 8 8 8 9 7]``````

If you specify a step size for the slice, broadcasting no longer works but you can replace the slice with an array containing the correct number of values..

``````import numpy as np

values = np.arange(1, 10)
print(values)

print(values[1:8:2])

values[1:8:2] = [0, 0, 0, 0]
print(values)``````
``````[1 2 3 4 5 6 7 8 9]
[2 4 6 8]
[1 0 3 0 5 0 7 0 9]``````

If you use advanced indexing, a copy is returned instead of a view, so you can’t use it to modify the original array.

``````import numpy as np

values = np.arange(1, 10)
print(values)

slice = values[[2, 4, 6]]
print(slice)

slice = [0, 0, 0]
print(values)``````
``````[1 2 3 4 5 6 7 8 9]
[3 5 7]
[1 2 3 4 5 6 7 8 9]``````

However, the following does work, because Python correctly figures out what you want to do. No view is actually created.

``````import numpy as np

values = np.arange(1, 10)
print(values)

values[[2, 4, 6]] = [0, 0, 0]
print(values)``````
``````[1 2 3 4 5 6 7 8 9]
[1 2 0 4 0 6 0 8 9]``````

Blog at WordPress.com.