Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 805
tknickman Avatar asked Feb 23 '26 23:02

tknickman


2 Answers

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.

like image 190
Sven Marnach Avatar answered Feb 25 '26 13:02

Sven Marnach


Use copy.deepcopy.

myList2 = copy.deepcopy(myList1)

See it working online: ideone

like image 39
Mark Byers Avatar answered Feb 25 '26 12:02

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!