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.

As you say, the iterator goes by index. This isn't really "solvable" the 
way you seem to expect because of how lists fundamentally work. Workarounds:

a) for x in L[:]: ... # makes a copy
b) remove from the end of the list...

If your list is big: Note that removing from the middle of a list is 
going to be expensive since the remainder of the list is copied for each 
iteration. You should consider alternative ways of expressing your 
algorithm (or, if you have to do this, look around for a linked list 
implementation for Python).

Removing from the end is cheap, so is removing from either end using 
collections.deque.

-- 
Dag Sverre

--~--~---------~--~----~------------~-------~--~----~
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