On Jan 29, 8:34 am, William McBrine <[EMAIL PROTECTED]> wrote:
> Look at this -- from Python 2.5.1:
>
> >>> a = [1, 2, 3, 4, 5]
> >>> for x in a:
>
> ...     if x == 3:
> ...         a.remove(x)
> ...     print x
> ...
> 1
> 2
> 3
> 5
>
> >>> a
> [1, 2, 4, 5]
>
> Sure, the resulting list is correct. But 4 is never printed during the
> loop!
>
(snipped)


If you're going to delete elements from
a list while iterating over it, then do
it in reverse order:

>>> a = [ 98, 99, 100 ]
>>> last_idx = len(a) - 1
>>> for i, x in enumerate(a[::-1]):
...     if x == 99: del(a[last_idx - i])
...     print x
...
100
99
98
>>> a
[98, 100]

--
Hope this helps,
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to