Skip to main content
How to Copy An Array In Python

How to Copy An Array In Python

in this post, we’ll let you know how to copy an array in python, we are not just copying values, also copying references.

Python array copy

In Python, use the assignment operator(=) to copy an array. However, there are two other ways to replicate the array.

  1. Shallow copy
  2. Deep copy

We believe the = operator creates a new object, but it does not. It just generates a new variable that shares the old object’s reference.

import numpy as np
source_arr = np.array([10, 11, 12, 13, 14])
#ids of the source array
print(id(source_arr))
#copy array
copied_arr = source_arr
#ids of the copied array
print(id(copied_arr))
#Changing the source array
source_arr[2] = 15
#Printing both arrays
print(source_arr)
print(copied_arr)

The source_arr and copied_arr array objects share the same reference. So whenever You’ll modify the original array, The change will apply to copied array too.

Output:

140428787462192
140428787462192
[10 11 15 13 14]
[10 11 15 13 14]

Shallow copy in Python

A bit-wise copy of the object is referred to as a shallow copy. The shallow copy of an object is a reference of other object. It means that any changes made to a copy of the object do reflect in the original object.

A new object is formed from an existing object, it has an exact replica of the old object’s values. Only the reference addresses are transferred.

import numpy as np
source_arr = np.array([10, 11, 12, 13, 14])
#ids of the source array
print(id(source_arr))
#copy array
copied_arr = source_arr
#ids of the copied array
print(id(copied_arr))
#Changing the source array
source_arr[2] = 15
#Printing both arrays
print(source_arr)
print(copied_arr)

Output:

140428787462192
140428787462192
[10 11 15 13 14]
[10 11 15 13 14]

Deep copy in Python

Deep copy is a recursive copying procedure. A copy of object is copied in other object. It means that any changes made to a copy of object do not reflect in the original object. You can implement deep copy feature in python using “deepcopy()” function.

import numpy as np
source_arr = np.array([10, 11, 12, 13, 14])
#ids of the source array
print(id(source_arr))
#copy array
copied_arr = source_arr.copy();
#ids of the copied array
print(id(copied_arr))
#Changing the source array
source_arr[2] = 15
#Printing both arrays
print(source_arr)
print(copied_arr)

Output:

139641029779504
139641029779600
[10 11 15 13 14]
[10 11 12 13 14]

Leave a Reply

Your email address will not be published. Required fields are marked *