Making a shallow copy of an array

Download python eBook


A quick way to make a copy of an array (as opposed to assigning a variable with another reference to the original array) is:


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[:]
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().


Contributors: 4
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook