Return to Snippet

Revision: 31951
at September 16, 2010 07:43 by magicrebirth


Initial Code
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

Initial URL
http://effbot.org/pyfaq/how-do-i-copy-an-object-in-python.htm

Initial Description

                                

Initial Title
How do I copy an object in Python?

Initial Tags
object, python, copy

Initial Language
Python