Create a Python list copy so that they are independent

Asked

Viewed 880 times

2

I have the following situation:

  • I have the list 1 with the following values [10,20,30,40]. I want to create a copy of this list, but I need the list_2 not to change when I modify some value of the list_1.

  • I have the following code below, but you are not doing what I need.


lista_1 = [10,20,30,40]
lista_2 = lista_1[:]

print (lista_2)

Thanks in advance.

1 answer

3


DOCS

The Difference between Shallow and deep copying is only Relevant for compound Objects (Objects that contain other Objects, like lists or class instances):

The difference between shallow and deep copy is only relevant to objects containing other objects, such as lists or instances of classes.

Just in case you presented, the way you did (Shallow copy, superficial copy) works well and is enough.

DEMONSTRATION

The best way to get one deep copy is:

import copy

lista_1 = [10,20,30,40]
lista_2 = copy.deepcopy(lista_1)
  • Thanks for the reply friend. But, that’s not what I need, because when I change the list_1 to list_2 also modifies. I need, that when modifying the list_1 to list_2 does not change. That is, unlinked lists.

  • I edited, @Danilo

  • Perfect Miguel. That’s what I needed. Thank you very much.

  • You’re welcome @Danilo

Browser other questions tagged

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