tags:

views:

129

answers:

2

Hi I want to copy a 2D list, so that if I modify 1 list, the other is not modified.

For 1 D list, I just do this:

a = [1,2]
b = a[:]

And now if I modify b, a is not modified.

But this doesn't work for 2D list:

a = [[1,2],[3,4]]
b = a[:]

If I modify b, a gets modified as well.

How do I fix this?

+5  A: 
b = [x[:] for x in a]
Ignacio Vazquez-Abrams
+1 since appropriate. I personally like avoiding copy / deepcopy (very very rarely had a valid use case for them in real life ; the same can be said for a list with more then 2 dimensions imo)
ChristopheD
+13  A: 

For a more general solution that works regardless of the number of dimensions, use copy.deepcopy():

import copy
b = copy.deepcopy(a)
Ayman Hourieh
Though in most cases, I'd probably say `from copy import deepcopy` since a name conflict is unlikely, and it looks nicer. ;)
Amber
@Dav, you make a valid point. I prefer to always import modules in order to avoid name conflicts instead of handling functions on a case-by-case basis. :)
Ayman Hourieh
Note that this will also deepcopy the actual elements in the lists.
FogleBird
@Dav, I disagree, it's generally better to use the module.function() format.
FogleBird
"Namespaces are one honking great idea -- let's do more of those!"
Xavier
@FogleBird: Personal preference.
Amber
@FogleBird: However, PEP-8 does actually seem to imply that `from ... import ...` is the norm unless there are namespace conflicts: http://www.python.org/dev/peps/pep-0008/ (see "Imports").
Amber
Read http://effbot.org/zone/import-confusion.htm for more information.
FogleBird
I don't see anything there which really applies here - mostly just a statement of opinion without support, and then a mention of potential circular or delayed import issues, which don't apply to the standard library nor, actually, most modules. In fact, the circular import issues section even explicitly notes that the problem doesn't require `from .. import` usage to manifest.
Amber