The copy Module
The copy module contains two functions that are used to copy objects, as shown in Example 1-64.
copy(object) => object creates a
“shallow” copy of the given object. In this context,
shallow means that the object itself is copied, but if the object is a
container, the members will still refer to the original member
objects.
Example 1-64. Using the copy Module to Copy Objects
File: copy-example-1.py import copy a = [[1],[2],[3]] b = copy.copy(a) print "before", "=>" print a print b # modify original a[0][0] = 0 a[1] = None print "after", "=>" print a print bbefore =>[[1], [2], [3]][[1], [2], [3]]after =>[[0], None, [3]][[0], [2], [3]]
You can also make shallow copies of lists using the [:] syntax (full slice), and you can make copies of dictionaries using the
copy method.
In contrast, deepcopy(object) => object creates
a “deep” copy of the given object, as shown in Example 1-65. If the object is a
container, all members are copied as well, recursively.
Example 1-65. Using the copy Module to Copy Collections
File: copy-example-2.py import copy a = [[1],[2],[3]] b = copy.deepcopy(a) print "before", "=>" print a print b # modify original a[0][0] = 0 a[1] = None print "after", "=>" print a print bbefore =>[[1], [2], [3]][[1], [2], [3]]after =>[[0], None, [3]][[1], [2], [3]]
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access