List being modified without implementation

Asked

Viewed 77 times

4

I’m having a problem where the list I’m working on is being modified even though there’s no value passing 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 the lista_inicial it is being modified.

I don’t know how to fix this.

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!

In doing lista_aux = lista_inicial you are indicating that lista_aux points to lista_inicial, not created a copy, 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 3, you can use the method copy.deepcopy:

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 it is a multidimensional list, may not function properly.

  • 1

    Thanks helped a lot. I spent a lot of time using equality as a way to copy.

Browser other questions tagged

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