The majority of objects in Python are passed around by reference rather than by value.
copy.copy() works for basic objects, but for containers like lists and dictionaries (or objects which maintain references to other objects) it will just copy the container, but the objects will still be references.
- Code: Select all
>>> a = range(0, 5)
>>> a
[0, 1, 2, 3, 4]
>>> b = range(5, 10)
>>> b
[5, 6, 7, 8, 9]
>>> c = [a, b]
>>> c
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> d = copy.copy(c)
>>> d
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> e = copy.deepcopy(c)
>>> e
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> c[0][0] = None
>>> c
[[None, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> d
[[None, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> e
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>>
So,
copy.copy(c) copies the array with references to the contained objects (represented by
d). When we change one of the elements contained in
c, the change is reflected in
d. However, it's not reflected in
e because we used
copy.deepcopy(c), which attempts to make copies of all objects contained in the
c container recursively.