Remove elements from a Python List

7

I have a problem with lists in python, I have a list in 2 different variables, with the same value .... but if I remove an element from any of the lists, the list that was to remain intact also has its element removed

listaUm = [1, 2, 3, 4]
listaDois = listaUm
listaDois.remove(3)
#listaDois [1, 2, 4]
#listaUm [1, 2, 4]
    
asked by anonymous 10.07.2015 / 20:33

3 answers

10

The listaDois reference is equal to listaUm , when you made listaDois = listaUm . So when you change one you are changing the other. Home Try to copy the array like this: listaDois = [n for n in listaUm]
EDIT: As suggested by @ drgarcia1986 in comments, an equivalent form is also:

  

ListDois = list (listUm)

    
10.07.2015 / 20:43
2

Use the statement del :

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

Source

    
10.07.2015 / 20:43
2

The problem with your solution is that both lists lists and list two refer to the same place in memory.

listaUm = [1, 2, 3, 4]
listaDois = listaUm.copy() # Tire uma copia da listaUm
listaDois.remove(3)
print(listaUm)
print(listaDois)

As output, it is expected [1,2,3,4] and [1,2,4].

Caution with the del command, since it should not be used in iterations, and may generate indexing errors

    
26.10.2016 / 00:02