kcrisman wrote:
> Dear support,
> 
> I'm trying to resolve #7315 and have discovered something that
> disturbs me, but probably is reasonable to someone who really
> understands Python lists.  Namely:
> 
> {{{
>>>> L=[1,2,3,4]
>>>> for x in L:
> ....     L.remove(x)
> ....     x
> ....     L
> ....
> 1
> [2, 3, 4]
> 3
> [2, 4]
>>>> L
> [2, 4]
> }}}
> 
> Somehow it is going by the index of the list, not the actual
> elements.  Assuming this is intended behavior, what is the right
> workaround?  Any link to the official Python documentation would be
> wonderful as well.


http://docs.python.org/reference/compound_stmts.html#the-for-statement

"There is a subtlety when the sequence is being modified by the loop 
(this can only occur for mutable sequences, i.e. lists). An internal 
counter is used to keep track of which item is used next, and this is 
incremented on each iteration. When this counter has reached the length 
of the sequence the loop terminates. This means that if the suite 
deletes the current (or a previous) item from the sequence, the next 
item will be skipped (since it gets the index of the current item which 
has already been treated). Likewise, if the suite inserts an item in the 
sequence before the current item, the current item will be treated again 
the next time through the loop. This can lead to nasty bugs that can be 
avoided by making a temporary copy using a slice of the whole sequence, 
e.g.,

for x in a[:]:
     if x < 0: a.remove(x)


Thanks,

Jason


--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support-unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to