remove elements incrementally from a list

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed May 19 10:06:44 EDT 2010


On Wed, 19 May 2010 03:53:44 -0700, Javier Montoya wrote:

> Dear all,
> 
> I've a list of float numbers and I would like to delete incrementally a
> set of elements in a given range of indexes, sth. like:
> 
> for j in range(beginIndex, endIndex+1):
>    print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j]
> 
> However, since I'm iterating over the same list, the indexes (range) are
> not valid any more for the new list. Does anybody has some suggestions
> on how to delete the elements properly?


Just delete the slice:

del myList[beginIndex:endIndex+1]

For small lists where you are deleting small chunks, this is the 
simplest, most straight-forward way.


Alternatively, create a new list excluding the bits you would have 
deleted, and assign it in place:

myList[:] = myList[:beginIndex] + myList[endIndex+1:]

Note carefully that you aren't just re-binding the name "myList", but 
assigning to the slice myList[:].

Then there is the old-fashioned way: iterate over the list backwards, 
deleting from the end towards the front.

for j in range(endIndex, beginIndex-1, -1):
    del myList[j]


If your list is HUGE and you have very little memory, this is probably 
the least worst way. It might be slow, but it will work.

Finally, we have this:

myList[beginIndex:] = myList[endIndex+1:]



-- 
Steven



More information about the Python-list mailing list