Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

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.

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode