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.Related posts
- An example using Python's groupby and defaultdict to do the same task — posted 2014-10-09
- python enum types — posted 2012-10-10
- Python data object motivated by a desire for a mutable namedtuple with default values — posted 2012-08-03
- How to sort a list of dicts in Python — posted 2010-04-02
- Python setdefault example — posted 2010-02-09
- How to conditionally replace items in a list — posted 2008-08-22