Shallow copies

You must be aware, however, that all of these techniques perform a shallow copy. That is, they create a new list containing references to the same objects as the source list, but they don't copy the referred-to objects. To demonstrate this, we'll use nested lists, with the inner lists serving as mutable objects. Here's a list containing two elements, each of which is itself a list:

>>> a = [ [1, 2], [3, 4] ]

We copy this list using a full slice:

>>> b = a[:]

And convince ourselves that we do in fact have distinct lists:

>>> a is bFalse

With equivalent values:

>>> a == bTrue

Notice, however, that the references within these distinct lists refer not only to equivalent objects:

>>> a[0][1, 2]>>> b[0][1, 2]

But, in fact, to the ...

Get The Python Apprentice now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.