What is the numpy array.copy() method in Python?

Overview

The array.copy() method in numpy is used to make and change an original array, and returns the two arrays.

Syntax

array.copy()

Parameters

The array.copy() method does not take any parameters.

Return value

The array.copy() method returns both the original and the modified array.

Example

from numpy import array
# creating an array
my_array = array([1, 2, 3, 4, 5])
# using the array.copy() method
new_array = my_array.copy()
# changing the 0 index of the array
my_array[0] = 9
print(my_array)
print(new_array)

Explanation

  • Line 1: We import array from numpy module.
  • Line 4: We use the array() method to create an array and assign its value to a variable my_array.
  • Line 7: We use the array.copy() method to copy the array, my_array, to a new array, new_array.
  • Line 10: We change the index 0 value of the array my_array to 9.
  • Line 11: We print the variable my_array.
  • Line 12: we print the variable new_array.

Note: The array.copy() method saves the old array even after it is modified.

Free Resources