10.3. Copying complex data structures

In the list examples of the above Section 10.2 we have given the example:

>>> L3 = L1[:]
and shown that L3 and L1 are not the same in memory
>>> L3 is L1
This is due to the fact that slicing a list creates a copy of a list and therefore L3 is only a copy of L1 but not the same object in memory.

Let's look at a second example with a nested list structure:

>>> L1 = [1, [2, 3], 4]
>>> L1
[1, [2, 3], 4]
>>> L2 = L1[:]
>>> L1 is L2
>>> L1[1] is L2[1]
Figure 10.5 illustrates what happens. In fact slicing creates only a shallow copy of compound objects by creating a new compound object and populating the new object with references to the members of the old list.

Figure 10.5. Copying nested structures