Python copy a list of lists

list, python

Solution

From the docs for the `copy` module:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

When you call regular `copy.copy()` you are performing a shallow copy. This means that in a case of a list-of-lists, you will get a new copy of the outer list, but it will contain the original inner lists as its elements. Instead you should use `copy.deepcopy()`, which will create a new copy of both the outer and inner lists.

The reason that you didn't notice this with your first example of using `copy([1,2])` is that the primitives like `int` are immutable, and thus it is impossible to change their value without creating a new instance. If the contents of the list had instead been mutable objects (like lists, or any user-defined object with mutable members), any mutation of those objects would have been seen in both copies of the list.

Problem

I'm using python 3.4.1. For a single list `a=[1,2]`, if I make a copy of it, `b = a.copy()` when I change items in `b`, it won't change items in `a`. However, when I define a list of lists (actually a matrix) `a = [[1,2],[3,4]]`, when I assign `b = a.copy()`. What I do to list `b` actually affects `a`. I checked their addresses, they are different. Can anyone tell me why? ps: What I did is `b[0][0] = x`, and the item in a was also changed.

Original source

Related problems