List as FIFO in for loop

malkarouri malkarouri at gmail.com
Sat Mar 8 17:01:16 CET 2008


On Mar 8, 3:20 pm, Roel Schroeven <rschroev_nospam... at fastmail.fm>
wrote:
> malkarouri schreef:
>
>
>
> > Hi everyone,
>
> > I have an algorithm in which I need to use a loop over a queue on
> > which I push values within the loop, sort of:
>
> > while not(q.empty()):
> >     x = q.get()
> >     #process x to get zero or more y's
> >     #for each y:
> >     q.put(y)
>
> > The easiest thing I can do is use a list as a queue and a normal for
> > loop:
>
> > q = [a, b, c]
>
> > for x in q:
> >     #process x to get zero or more y's
> >     q.append(y)
>
> > It makes me feel kind of uncomfortable, though it seems to work. The
> > question is: is it guaranteed to work, or does Python expect that you
> > wouldn't change the list in the loop?
>
> Changing a loop while iterating over it is to be avoided, if possible.
> In any case, a deque is more efficient for this kind of use. I'd use it
> like this:
>
> from collections import deque
>
> q = deque([a, b, c])
> while q:
>      x = q.popleft()
>      # ...
>      q.append(y)
>
> --
> The saddest aspect of life right now is that science gathers knowledge
> faster than society gathers wisdom.
>    -- Isaac Asimov
>
> Roel Schroeven

Thanks for your response. My same feeling, avoid loop variable, but no
explicit reason.
Thanks for reminding me of the deque, which I never used before.
Alas, in terms of efficiency - which I need - I don't really need to
pop the value on the list/deque.
This additional step takes time enough to slow the loop a lot. So its
not ideal here.

Still, why avoid changing loop variable? Does python treat looping
over a list differently from looping over an iterator, where it
doesn't know if the iterator future changes while loop running?

Regards,

Muhammad Alkarouri



More information about the Python-list mailing list