6.8. Copying Objects
As we saw in the last section, the default behavior of assignment operations in Python is to make references to objects rather than to create duplicate copies of objects.
So, what if you really do need to make a copy of a list, for example? Python provides a module, known as copy, that can copy arbitrary data structures.
CD-ROM reference=6033.txt >>> import copy >>> x = [1,2,3] >>> print x [1, 2, 3] >>> y = copy.copy(x) >>> print y [1, 2, 3] >>> print id(x) 8376864 >>> print id(y) 8378848 >>> x is y 0
The copy module can also deal with nested list structures. It provides a deepcopy method that recursively handles objects contained within other objects.
CD-ROM reference=6034.txt >>> import copy >>> x = [1,2,["Button my ...
Get XML Processing with Python 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.