deleting items within a for loop - mutable indices

Erik Max Francis max at alcyone.com
Fri Apr 23 23:06:13 EDT 2004


SnuSnu wrote:

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

The solution is usually to either iterate over an explicit copy of the
list, or use functional means to build the final list up from the
original list without mutating it at all.

In this case it's probably best to just iterate backwards over the
indices, since you know what you're getting and can control the order in
which you delete the items.

> deletion_list.sort()
> deletion_list.reverse()
> # BTW: It's a shame I can't do deletion_list.sort().reverse()

This is a deliberate design decision.  These methods are made to return
None so you're explicitly aware that they mutate the object, rather than
return a duplicate.  You can always define your own functional version:

	def mySort(seq):
	    result = seq[:]
	    result.sort()
	    return result

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Awards are merely the badges of mediocrity.
    -- Charles Ives



More information about the Python-list mailing list