Remove elements from a Python List

Asked

Viewed 17,968 times

12

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

listaUm = [1, 2, 3, 4]
listaDois = listaUm
listaDois.remove(3)
#listaDois [1, 2, 4]
#listaUm [1, 2, 4]

4 answers

15


The reference of listaDois is equal to that of the listaUm, when you did listaDois = listaUm. So when it changes one is changing the other.

Try to copy the array this way: listaDois = [n for n in listaUm]

EDIT: As suggested by @drgarcia1986 in the comments, an equivalent form is also:

listDois = list(list one)

  • Thank you very much, solved my problem!

  • 7

    an easier way is listaDois = list(listaUm)

  • Why does this happen? What is this reference that is being copied? It could develop this part better?

9

The problem with your solution is that both lists (listaUm and listaDois) reference 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, is expected [1,2,3,4] and [1,2,4].

Watch out for the remote del, because it should not be used in iterations, which can generate indexing errors

3

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

  • 1

    tried with del, and gave the same problem... but the solution from above gave right, vlw by the help

0

One of the valid ways to solve this problem is by performing a deep copy of list one.

This process can be obtained using the method deepcopy library copy

OBSERVING:

A deep copy builds a new composite object and then recursively inserts copies of the objects found in the original.

This way we can implement the following code:

from copy import deepcopy

listaUm = [1, 2, 3, 4]
listaDois = deepcopy(listaUm)
listaDois.remove(3)

print(listaUm)
print(listaDois)

Note that this code initially defines listDois as a deep copy of list one. Thus, listDois is a faithful copy of list one only at another memory address.

Then, from this moment we may remove any value from listDois without interfering with list one.

Executing said code, we obtain as output:

[1, 2, 3, 4]
[1, 2, 4]

Browser other questions tagged

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