How to clone a list with Python 3?

Asked

Viewed 454 times

3

From list m:

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

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

What I’m not seeing or don’t know about it?

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 won’t be enough.

To copy the mutable objects from your list, so they don’t keep the reference, you will need to make the deep copy.

So just do:

from copy import deepcopy

mb = deepcopy(m)

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 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 a copy of it, that is to say, changing the copy does not change the original.

  • 2

    It will have the same problem as the other answer, which was deleted. What it has is a list of lists, which are mutable types. Even making the copy shallow, with copy, the references of the internal objects will remain in the new list. If one of them is changed, the change will be reflected in the original. See: https://repl.it/@acwoss/Disfiguredstrictbase

Browser other questions tagged

You are not signed in. Login or sign up in order to post.