Function Syntax
The function syntax is as shown below:
Parameters
- a – refer to the input array.
- order – Determines the memory layout of the copy. Accepted values are ‘C’ for C-order, ‘F’ for F-order, ‘A’ means ‘F’ if the input array is a Fortran contiguous and C if otherwise, and ‘K’ for matching the input array.
- subok – a Boolean value that determines if the sub-classes are passed through. By default, this value is set to False.
Return Value
The function returns an array copy of the specified input.
Example 1
Consider the example shown below:
arr = np.array([12,34,56])
arr_copy = np.copy(arr)
print(arr_copy)
The above should return the same elements as the variable ‘arr’ as ‘arr_copy’ holds the copy of the input array.
The result is as shown:
Example 2
Let us take another example.
arr_2 = arr
arr_copy = np.copy(arr)
print(f"arr: {arr}\narr_2: {arr_2}\narr_copy: {arr_copy}")
In this case, arr_2 holds a reference to the arr and arr_copy holds a copy of the array ‘arr’.
If you make changes to the original arr, the reference arr_2 will be affected by the changes while the copy will not.
For example:
arr_2 = arr
arr_copy = np.copy(arr)
print(f"arr: {arr}\narr_2: {arr_2}\narr_copy: {arr_copy}")
arr[0] = 78
print(f"arr: {arr}\narr_2: {arr_2}\narr_copy: {arr_copy}")
The code above should return:
arr_2: [12 34 56]
arr_copy: [12 34 56]
arr: [78 34 56]
arr_2: [78 34 56]
arr_copy: [12 34 56]
Notice how the changes to the arr variable affect the array ‘arr_2’.
Final
For this one, we covered the basics of using the array.copy function to create an array copy an input.
Happy coding!!