Shallow copying

If a container object (an object—such as a list, tuple, or dictionary—that holds other objects) contains lists, then making a copy of the container object by using newcontainer = oldcontainer or newcontainer = oldcontainer[:] doesn't make a copy of the lists it contains. The new container continues to refer to the original lists. This is called shallow copying, and Python uses it because (among other reasons) it saves resources. The following example illustrates shallow copying. The larder list changes when one of the lists inside the food list is changed:

>>> breakfast = ['spam'

1 , 'baked beans

']

>>> basket = ['peach',

'apple', 'gooseberries']

>>> food = [breakfast,

basket]

>>> larder = food

>>> larder

[['spam', 'baked beans'

1 ], ['peach', '

apple', 'gooseberries']]

>>> del basket[0]

>>> larder

[['spam', 'baked beans'

1 ], ['apple', '

gooseberries']]

Was this article helpful?

0 0

Post a comment