How do I copy an object in Python?


/ Published in: Python



Copy this code and paste it in your HTML
  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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.