???? i can`t understand it

David C. Fox davidcfox at post.harvard.edu
Fri Aug 8 08:44:24 EDT 2003


Enrique wrote:
>  >>> a=[1,2,3,4,5]
>  >>> for b in a:
> ...  a.remove(b)
> ...  
>  >>> a
> [2, 4]
>  >>>

As others have noted, modifying a sequence can have strange effects on 
iterators.

Presumably, the example above is simplified (since if you really wanted 
to remove all elements in a, you would just say a = []).  If you want to 
selectively remove elements in a, you should have a look at the built-in 
function filter.  For example, to remove elements < 0:

a = [1,5,7, -4, 2, -10]
a = filter(lambda x: x >= 0, a)

David





More information about the Python-list mailing list