Posted By

magicrebirth on 09/16/10


Tagged

object python copy deepcopy


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

gartenstuhl


How do I copy an object in Python?


 / Published in: Python
 

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

  1. Try copy.copy or copy.deepcopy for the general case. Not all objects can be copied, but most can.
  2.  
  3. import copy
  4.  
  5. newobj = copy.copy(oldobj) # shallow copy
  6. newobj = copy.deepcopy(oldobj) # deep (recursive) copy
  7. Some objects can be copied more easily. Dictionaries have a copy method:
  8.  
  9. newdict = olddict.copy()
  10. Sequences can be copied by slicing:
  11.  
  12. new_list = L[:]
  13. You can also use the list, tuple, dict, and set functions to copy the corresponding objects, and to convert between different sequence types:
  14.  
  15. new_list = list(L) # copy
  16. new_dict = dict(olddict) # copy
  17.  
  18. new_set = set(L) # convert list to set
  19. new_tuple = tuple(L) # convert list to tuple

Report this snippet  

You need to login to post a comment.