How to make a copy of the Python array
Learn how to make a copy of a Python array, with example code showing how to use slicing and the copy module.
Creating a Copy of a Python Array
In Python, creating a copy of an array can be done in several ways. The most common and straightforward way is to use the built-in list.copy()
method. This method creates a shallow copy of the original array, meaning that the elements of the copy are references to the original array.
# Original array
my_array = [1, 2, 3, 4, 5]
# Create copy of array using list.copy()
my_array_copy = my_array.copy()
# Verify that they are different objects
print(my_array is my_array_copy) # False
# Verify that the elements in the two arrays are the same
print(my_array == my_array_copy) # True
Another method of creating a copy of an array is to use the list()
constructor. This method creates a new list object from the elements of the original array. It is important to note that this method creates a shallow copy of the original array, just like the list.copy()
method.
# Original array
my_array = [1, 2, 3, 4, 5]
# Create copy of array using list()
my_array_copy = list(my_array)
# Verify that they are different objects
print(my_array is my_array_copy) # False
# Verify that the elements in the two arrays are the same
print(my_array == my_array_copy) # True
Finally, another method of creating a copy of an array is to use the built-in slicing
syntax. This method creates a shallow copy of the original array, just like the previous two methods. The advantage of this method is that it is more concise and easier to read.
# Original array
my_array = [1, 2, 3, 4, 5]
# Create copy of array using slicing
my_array_copy = my_array[:]
# Verify that they are different objects
print(my_array is my_array_copy) # False
# Verify that the elements in the two arrays are the same
print(my_array == my_array_copy) # True
In summary, there are several ways to create a copy of an array in Python. The most common and straightforward way is to use the built-in list.copy()
method. Another method is to use the list()
constructor. Finally, there is the more concise slicing syntax. All of these methods create a shallow copy of the original array.