10.12. Cloning Lists

If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word copy.

The easiest way to clone a list is to use the slice operator.

Taking any slice of a creates a new list. In this case the slice happens to consist of the whole list.

Python 2.7
1a = [81, 82, 83]
2
3b = a[:]       # make a clone using slice
4print(a == b)
5print(a is b)
6
7b[0] = 5
8
9print(a)
10print(b)
Step 1 of 7
line that has just executed

next line to execute

Frames
Objects

(chp09_is4)

Now we are free to make changes to b without worrying about a. Again, we can clearly see in codelens that a and b are entirely different list objects.

Next Section - 10.13. Repetition and References