Create a list copy in Python so that they are independent

2

I have the following situation:

  • I have list_1 with the following values [10,20,30,40]. I want to create a copy of this list, however I need the list_2 not to change when I modify some value in 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)

Thank you in advance.

    
asked by anonymous 04.03.2017 / 01:01

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 superficial and deep copy is only relevant for objects that contain other objects, such as lists or instances of classes.

For the specific case you've submitted, the way you did (shallow copy) is fine and that's enough.

DEMONSTRATION

The best way to get a deep copy is:

import copy

lista_1 = [10,20,30,40]
lista_2 = copy.deepcopy(lista_1)
    
04.03.2017 / 01:07