List iterator thread safety

Hendrik van Rooyen hendrik at microcorp.co.za
Thu Aug 27 16:25:54 CEST 2009


On Thursday 27 August 2009 15:26:04 Carl Banks wrote:

> Deleting items from a list while iterating over it is a bad idea,
> exceptions or not.
>
> Hmm, this sounds like something someone might do for a game.  You have
> a list of objects, and in a given time step you have to iterate
> through the list and update each object.  Problem is, one of the
> enemies is kill before you get to it, so you would like to remove the
> object from the list while iterating.  Not an easy problem.

Its not too bad - if you crook a bit - the trick is that you iterate over the 
list backwards when you are removing stuff based on index, so that the 
remainder does not get jumbled up by losing their positions, as happens when 
you do it going forwards.

- Hendrik



More information about the Python-list mailing list