deleting items within a for loop - mutable indices

Dan Bishop danb_83 at yahoo.com
Sat Apr 24 03:51:35 EDT 2004


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).

for i in deletion_list:
   x[i] = None
x = [num for num in x if num is not None]



More information about the Python-list mailing list