a shot of dev knowledge

Related tags

# What is the difference between copy() and view() in Numpy?

### What is copy() and view() in NumPy?

Both copy() and view() are used to copy data and then perform operations on itthe copied data.

The only difference between these two functions is that the copy() function will create a separate NumPy array (if you make any changes in this copied array, it will not affect original array, and vice-versachanges made to the original array will not affect the copied array). But, with the view() function there will not be a separate NumPy array and, if you make any changes to this new array, it will affect the original array and vice-versachanges made to the original array will affect the new array.

### How to verify the difference between copy() and view()

Take a look at the code snippet below – it verifies the difference we discussed above.

import numpy as np

print('copy() function usage')
numpy_array = np.array([1,2,3,4,5])
print('Original NumPy array: ',numpy_array)
copy_array = numpy_array.copy()
numpy_array[0] = 42
print('Updated NumPy array: ',numpy_array)
print('Copied NumPy array: ',copy_array)

print('view() function usage')
numpy_array = np.array([1,2,3,4,5])
print('Original NumPy array: ', numpy_array)
view_array = numpy_array.view()
numpy_array[0] = 99
print('Updated NumPy array: ',numpy_array)
print('View NumPy array: ',view_array)
Difference between copy() and view() function in NumPy

Explanation:

• On line 1, we import the required package.

• On line 4, we create a NumPy array that contains 5 elements.

• On line 6, we use the copy() function to create a copy of the array created in the previous step.

• On line 7, we update one element in the original array.

• On lines 8 and 9, we print those two arrays to see the elements in the arrays.

We can see that there was a change in the original array, but it did not affect the copied array.

• On line 12, we create a NumPy array that contains 5 elements.

• On line 14, we use the view() function to create a view of the array created in the previous step.

• On line 15, we update one element in the original array.

• On lines 16 and 17, we print those two arrays to see the elements in the arrays.

We can see that there was a change in the original array and in the view array.

This confirms the difference between copy() and view() function.

Related tags

RELATED COURSES
Related Courses
Related Courses

#### Keep Exploring

Learn in-demand tech skills in half the time