How to copy Python lists or other objects



This is my OLD blog. I've copied this post over to my NEW blog at:

http://www.saltycrane.com/blog/2007/11/how-to-copy-python-lists-or-other/

You should be redirected in 2 seconds.



This problem had me stumped for a while today. If I have a list a, setting b = a doesn't make a copy of the list a. Instead, it makes a new reference to a. For example, see the interactive Python session below:

Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3]
>>> b = a
>>> b
[1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>> 

Here is a quick reference extracted from Chapter 9 in Learning Python, 1st Edition.

To make a copy of a list, use the following:
newList = myList[:]
newList2 = list(myList2)         # alternate method

To make a copy of a dict, use the following:
newDict = myDict.copy()

To make a copy of some other object, use the copy module:
import copy
newObj = copy.copy(myObj)        # shallow copy
newObj2 = copy.deepcopy(myObj2)  # deep copy

For more information on shallow and deep copies with the copy module, see the Python docs.

No comments:

About

This is my *OLD* blog. I've copied all of my posts and comments over to my NEW blog at:

http://www.saltycrane.com/blog/.

Please go there for my updated posts. I will leave this blog up for a short time, but eventually plan to delete it. Thanks for reading.