Making a shallow copy of an array

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Indexing and Slicing:
* Making a shallow copy of an array

Table Of Contents
2 Filter
3 List
7 Loops
19 Indexing and Slicing
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve