HOW TO CREATE COPY OF ARRAY IN PYTHON NUMPY?

Creating copy of an array in Python NumPy-

We can create copy of an array in Python NumPy by using copy() method. The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy.

import numpy as np

arr = np.array([1, 2, 3, 4])
x = arr.copy()
arr[0] = 9

print(arr)
print(x)

Output-

[9 2 3 4]
[1 2 3 4]

Explanation-

x = arr.copy() – it will create a copy of arr and assign it to variable x

arr[0]=9 – it will change the first element of array arr

changes made in original array after creation of copy of arr will not impact the content of copied array x, it shows that x owns the data.


Posted

in

Tags:

Comments

Leave a Reply