A quick way to make a copy of an array (as opposed to assigning a variable with another reference to the original array) is:
arr[:]
Let's examine the syntax. [:]
means that start
, end
, and slice
are all omitted. They default to 0
, len(arr)
, and 1
, respectively, meaning that subarray that we are requesting will have all of the elements of arr
from the beginning until the very end.
In practice, this looks something like:
arr = ['a', 'b', 'c']
copy = arr[:]
arr.append('d')
print(arr) # ['a', 'b', 'c', 'd']
print(copy) # ['a', 'b', 'c']
As you can see, arr.append('d')
added d
to arr
, but copy
remained unchanged!
Note that this makes a shallow copy, and is identical to arr.copy()
.