Is this a safe thing to do?

David C. Fox davidcfox at post.harvard.edu
Thu Oct 9 10:47:12 EDT 2003


Phil Schmidt wrote:
> The following example works fine (Python 2.3), but is it always safe
> to modify a list that is being iterated in a loop, regardless of the
> actual contents of the list x? If not, what's a better (safe) way to
> do it?
> 
> Thanks!
> 
> 
> 
>>>>x=[{'f':9},{'f':1},{1:3,'f':9},{'f':3}]
>>>>for t in x:
> 
> 	if t['f'] == 9:
> 		x.remove(t)
> 
> 		
> 
>>>>x
> 
> [{'f': 1}, {'f': 3}]


This is generally not safe.  Another way to do it is

x = filter(lambda t: t['f'] != 9, x)

which creates a new list out of all elements t satisfying t['f'] not 
equal to 9, and then assigns the new list back to x.

David





More information about the Python-list mailing list