???? i can`t understand it

Peter Abel p-abel at t-online.de
Fri Aug 8 11:31:38 EDT 2003


Sean 'Shaleh' Perry <shalehperry at comcast.net> wrote in message news:<mailman.1060332014.18871.python-list at python.org>...
> On Friday 08 August 2003 01:11, Enrique wrote:
> > >>> a=[1,2,3,4,5]
> > >>> for b in a:
> >
> > ...  a.remove(b)
> > ...
> >
> > >>> a
> >
> > [2, 4]
> 
> does this help??
> 
> >>> a = range(1,6)
> >>> for b in a:
> ...     print b
> ...     a.remove(b)
> ... 
> 1
> 3
> 5
> >>> a
> [2, 4]
> 
> I read this as "do not remove items from a list you are iterating over".  
> Pretty sure the docs comment on this as well.
> 
> What seems to happen is b = 1, 1 is removed from a.  b should then be 2.  But 
> the internal counter skips it and goes to 3.  So what i see happening is:
> 
> next = 0
> for b = a(next):
>     a.remove(b)
>     next += 1
> 
> so a[1] is 3 when we expect it to be 2 because 2 is now at index a[0].

Or start removing from the end:
>>> a=[1,2,3,4,5]
>>> for i in range(len(a)-1,-1,-1):
... 	a.remove(a[i])
... 	print a
... 	
[1, 2, 3, 4]
[1, 2, 3]
[1, 2]
[1]
[]

Regards
Peter




More information about the Python-list mailing list