/ Published in: Python
URL: http://effbot.org/pyfaq/how-do-i-copy-an-object-in-python.htm
Expand |
Embed | Plain Text
Try copy.copy or copy.deepcopy for the general case. Not all objects can be copied, but most can. import copy newobj = copy.copy(oldobj) # shallow copy newobj = copy.deepcopy(oldobj) # deep (recursive) copy Some objects can be copied more easily. Dictionaries have a copy method: newdict = olddict.copy() Sequences can be copied by slicing: new_list = L[:] You can also use the list, tuple, dict, and set functions to copy the corresponding objects, and to convert between different sequence types: new_list = list(L) # copy new_dict = dict(olddict) # copy new_set = set(L) # convert list to set new_tuple = tuple(L) # convert list to tuple
You need to login to post a comment.
