Python Language Indexing and Slicing Making a shallow copy of an array

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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().



Got any Python Language Question?