deleting items within a for loop - mutable indices

Henk-Jan de Jong henkjan at xs4all.nl
Sat Apr 24 14:12:59 EDT 2004


Hello,

this should work:

for i in deletion_list:
    x.remove(i)

Matuka

"SnuSnu" <snusnu at tiscali.co.uk> wrote in message
news:4089cb21$1_2 at mk-nntp-2.news.uk.tiscali.com...
> Okay - here's a (probably) really easy question:
>
> I can't do the following, so what's the best way to handle this
> case of wanting to delete within a loop?
>
> x = [0,1,2,3,4,5,6,7,8]
> deletion_list = [2,7,8]
>
> for i in deletion_list:
>   del x[i]
>
> This obviously doesn't work because the list keeps changing
> each time I delete something, so the indices are no longer valid
> after the first delete (so I get an IndexError on teh last delete).
>
> My hack is to do this first (which makes sure that the higher indices
> are deleted first), but this is not very elegant or quick:
>
> deletion_list.sort()
> deletion_list.reverse()
> # BTW: It's a shame I can't do deletion_list.sort().reverse()
>
> Is there a simple solution?
>
> (It would be nice to do something like
>   del x[2,7,8]           # or..
>   del [*deletion_list]
> )
>
> Thanks.
>





More information about the Python-list mailing list