deleting items within a for loop - mutable indices

SnuSnu snusnu at tiscali.co.uk
Fri Apr 23 22:02:38 EDT 2004


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