tknickman
tknickman

Reputation: 4621

Duplicate a list of lists in python?

I need to be able to duplicate a list of lists in python.

so for example right now I have a function that returns a list.

this is always lists within a list.

for example:

 myList = [[1,2,3],[4,5,6],[7,8,9]]

now I need to create two copies of this list (myList1, and myList2), each of which is separately mutable (for example, if I edit myList1, myList2 will not be edited)

I have tried everything.

from the simple:

 myList1 = myList[:]
 myList2 = myList[:]

to the more complicated:

 myList1 = []
 for ch in myList:
      myList1.append(ch)


 myList2 = []
 for ch in myList:
      myList2.append(ch)

nothing works. If I change a value in one list:

 myList1[0][0] = 10

both lists become:

 [[10,2,3],[4,5,6],[7,8,9]]

Any idea how to do this?

Upvotes: 2

Views: 228

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601351

Everything you have tried so far only creates a shallow copy of the outer list. To create a deep copy, use either

copied_list = [x[:] for x in my_list]

using a list comprehension or

copied_list = copy.deepcopy(my_list)

using the copy.deepcopy() function.

Upvotes: 8

Mark Byers
Mark Byers

Reputation: 837916

Use copy.deepcopy.

myList2 = copy.deepcopy(myList1)

See it working online: ideone

Upvotes: 3

Related Questions