How to clone a list with Python 3?

3

From list m :

 m =   [[' # ', ' # ', ' # ', ' # ', ' # ', ' # '], [' # ', ' # ', ' # ', ' # ', ' # ', ' # '], [' # ', ' # ', ' # ', ' # ', ' # ', ' # '], [' # ', ' # ', ' # ', ' # ', ' # ', ' # '], [' # ', ' # ', ' # ', ' # ', ' # ', ' # '], [' # ', ' # ', ' # ', ' # ', ' # ', ' # ']]

When doing mb = m[:] or mb = list(m) I would clone the m initial, right or not? But by doing mb[0][0] = 99999999 , for example, the m list is also modified.

What do I not see or do not know about?

    
asked by anonymous 28.08.2018 / 19:54

2 answers

3

The main problem is that you have a list of mutable objects - in this case, a list of lists. So just making a shallow copy will not be enough.

To copy the mutable objects from your list, so that they do not keep the reference, you need to do the deep copy.

So, just do:

from copy import deepcopy

mb = deepcopy(m)
    
28.08.2018 / 21:03
0

There are several possibilities:

>>> lista = [1, 2, 3]
>>> copia = lista.copy()
>>> copia
[1, 2, 3]
>>> copia = lista[:]
>>> copia
[1, 2, 3]

In addition to what in many scripts you are able to see something like:

lista = [1, 2, 3]
copia = []
for item in lista:
    copia.append(item)
print(copia) # [1, 2, 3]

Something contrary to what you said to do lista[:] does not generate a reference to the original list, but rather a copy of it, ie change the copy does not change the original.

    
28.08.2018 / 20:59