properly delete item during "for item in..."

Duncan Booth duncan.booth at invalid.invalid
Thu Jul 17 19:27:22 CEST 2008


mk <mrkafk at gmail.com> wrote:

> Iterating over a copy may _probably_ work:
> 
> >>> t=['a', 'c', 'b', 'd']
> >>>
> >>> for el in t[:]:
>      del t[t.index(el)]
> 
>      
> >>> t
> []
> 
> 
> However, is it really safe? Defining safe as "works reliably in every 
> corner case for every indexable data type"?

No, because you cannot necessarily copy every indexable data type using 
t[:], and not all types will support index. Also it is inefficient to 
delete from the start of the list.

If you are working with a list and deleting every object:

    del t[:]

will suffice.

If you don't want to delete everything then you could do:

for index, el in enumerate(reversed(t)):
    if not wewant(el):
    	   del t[index]

but the pythonic way is just:

 t[:] = [ el for el in t if wewant(el) ]

or if you just want the filtered list and don't care about updating the 
original:

 t = [ el for el in t if wewant(el) ]


> Con: suppose the data structure t is really, really big. Just deleting 
> some items from t temporarily doubles the memory consumption.

No it doesn't. Copying a list doesn't copy any of the elements in the list, 
it just copies the references to those element.



More information about the Python-list mailing list