SaltyCrane Blog — Notes on JavaScript and web development

How to copy Python lists or other objects

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.

Comments