Having trouble deleting objects from a list...

Jason Stitt jason at pengale.com
Wed Oct 19 21:48:30 EDT 2005


On Oct 19, 2005, at 8:16 PM, KraftDiner wrote:
> I have a list, and within it, objects are marked for deletion.
> However when I iterate through the list to remove objects
> not all the marked objects are deleted..
> here is a code portion:
>
>             i = 0
>             for obj in self.objList:
>                 if obj.mouseHit:
>                     print 'delete + ' + `i`
>                     self.objList.pop(i)
>                     flag = True
>                 else:
>                     i = i + 1
>                 print `i`

You're mixing two different ways of looping, and they're getting out  
of sync.

'for obj in self.objList' will keep right on iterating through the  
list even if you don't increment i.

A direct adaptation of your code that should work is:

i = 0
while i < len(self.objList):
     if self.objList[i].mouseHit:
         self.objList.pop(i)
         flag = True
     else:
         i += 1

Or, shorter and a bit more Pythonic, but not in-place:

newObjList = [obj for obj in self.objList if not obj.mouseHit]
flag = (len(newObjList) != len(self.objList))
self.objList = newObjList

I don't know how the performance of the two would compare. The second  
involves creating a new list, but Python is supposed to optimize the  
heck out of list comprehension, and removing items from a list in  
place isn't free, either.

Jason




More information about the Python-list mailing list