List being modified without implementation

4

I have a problem where the list I am working on is being modified even though there is no passing of values to it.

from random import *
from numpy import *   

m=2

lista_inicial=[[1, 2], [0, 2], [0, 1]]

lista_aux = []

lista_aux = lista_inicial

print "condiçao inicial", lista_inicial

probabilidade =[0.3333333333333333, 0.3333333333333333, 0.3333333333333333]

novo_elemento=[]

tamanho_lista_adjacencia= len(lista_inicial)

for i in range(m):

    valor_soma=[]

    aleatorio= random.random()

    soma=0

    for j in range(tamanho_lista_adjacencia):

        valor_soma.append(probabilidade[j])

        soma= sum(valor_soma)

        if(soma>=aleatorio):

            novo_elemento.append(j)

            lista_aux[j].append(tamanho_lista_adjacencia)

            break

novo_elemento.sort()

print "Lista auxiliar:", lista_aux
print "Lista Inicial:", lista_inicial

As you can see, even without passing values / implementing lista_inicial it is being modified.

I do not know how to solve this.

    
asked by anonymous 14.09.2016 / 14:11

1 answer

5

The problem occurs in the section below:

lista_inicial = [[1, 2], [0, 2], [0, 1]]
lista_aux = []

lista_aux = lista_inicial # Aqui!

When you do lista_aux = lista_inicial you are indicating that lista_aux points to lista_inicial , a copy is not created, you are just adding another name that points to the original list in memory.

Therefore, any changes made to lista_aux will also be visible in lista_inicial .

To copy a list , in Python 2 and < in> 3 , you can use the copy.deepcopy method:

import copy

lista_inicial = [[1, 2], [0, 2], [0, 1]]
lista_aux = copy.deepcopy(lista_inicial)

Another alternative, in this case is:

lista_inicial = [[1, 2], [0, 2], [0, 1]]

lista_aux = [x[:] for x in lista_inicial]

There are other ways to copy a list , but in this case because it is a multidimensional list , may not work properly.

    
14.09.2016 / 15:20