NumPy Tutorial NumPy Statistics NumPy References

NumPy - ndarray.copy() function



The NumPy ndarray.copy() returns a copy of the array. The syntax for using this function is given below:

Syntax

numpy.ndarray.copy(order='C')

Parameters

order Optional. Specify the memory layout of the copy. It can take values from {'C', 'F', 'A', 'K'}. The default is 'C'.
  • 'C' - for C order (row major).
  • 'F' - for F order (column major).
  • 'A' - F if a is Fortran contiguous, C otherwise.
  • 'K' - match the layout of a as closely as possible.

Return Value

Returns a copy of the array.

Example:

In the example below, ndarray.copy() is used to copy a given array.

import numpy as np

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

#creating a copy of array x
y = x.copy()

#displaying array x
print("id of x =", id(x))
print("x =")
print(x)

#displaying array y
print("\nid of y =", id(y))
print("y =")
print(y)

#changing content of y
#this will change y but not x
y[0,0] = 100

#after operation, array x
print("\nx =")
print(x)

#after operation, array y
print("\ny =")
print(y)

The output of the above code will be:

id of x = 140389488063664
x =
[[1 2 3]
 [4 5 6]]

id of y = 140389488066448
y =
[[1 2 3]
 [4 5 6]]

x =
[[1 2 3]
 [4 5 6]]

y =
[[100   2   3]
 [  4   5   6]]

❮ NumPy - Functions