How to make a copy of the array in Python
Learn how to make a copy of an array in Python with an example, from shallow to deep copying.
Making a Copy of an Array in Python
Making a copy of an array in Python is a straightforward process. We can use the built-in method list.copy()
or the operator []
to copy an array. Let's go over how to use each of these methods.
Using list.copy()
Using the list.copy() method is the simplest way to make a copy of an array. List.copy() returns a shallow copy of the array, meaning that it only copies the values of the array, not the references. Here is an example of how to use list.copy():
# Create an array
my_array = [1, 2, 3, 4, 5]
# Make a copy of the array
my_array_copy = my_array.copy()
# Print out the copy of the array
print(my_array_copy)
# Output: [1, 2, 3, 4, 5]
As you can see, the copy of the array is exactly the same as the original array.
Using the Operator []
We can also use the operator []
to copy an array. This method is slightly more complex than the list.copy()
method, but it is still relatively straightforward. Here is an example of how to use the operator []
to make a copy of an array:
# Create an array
my_array = [1, 2, 3, 4, 5]
# Make a copy of the array
my_array_copy = my_array[:]
# Print out the copy of the array
print(my_array_copy)
# Output: [1, 2, 3, 4, 5]
As you can see, the result of using the operator [] is the same as the result of using list.copy()
- a shallow copy of the array.
In summary, making a copy of an array in Python is a straightforward process. We can use either the list.copy()
method or the operator []
to make a shallow copy of the array. Both of these methods are relatively easy to use and understand.