See All Titles |
![]() ![]() copyThe copy module provides shallow and deep object copying operations for lists, tuples, dictionaries, and class instances. copy.copy()This function creates a shallow copy of the x object. >>> import copy >>> x = [1, 2, 3, [4, 5, 6]] >>> y = copy.copy(x) >>> print y [1, 2, 3, [4, 5, 6]] >>> id(y) == id(x) 0 As you can see at the end of the previous example, the new list is not the old one. As you can see, this function provides the same result that y=x[:] does. It creates a new object that references the old one. If the original object is a mutable object and has its value changed, the new object will change too. copy.deepcopy()It recursively copies the entire object. It really creates a new object without any link to the original structure. basic syntax: variable = copy.deepcopy(object) >>> import copy >>> listone = [{ "name":"Andre"} , 3, 2] >>> listtwo = copy.copy(listone) >>> listthree = copy.deepcopy(listone) >>> listone[0]["name"] = "Renata" >>> listone.append("Python") >>> print listone, listtwo, listthree [{ "name":"Renata"} , 3, 2, "Python"] [{ "name":"Renata"} , 3, 2] [{ "name":"Andre} , 3, 2]
|
Index terms contained in this sectionlibrariesPython Services Python Services syntax functions copy.deepcopy() |
© 2002, O'Reilly & Associates, Inc. |