List as FIFO in for loop

Paul Hankin paul.hankin at gmail.com
Sat Mar 8 18:55:29 EST 2008


On Mar 8, 10:42 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
> On Mar 8, 9:43 am, malkarouri <malkaro... at gmail.com> wrote:
>
> > 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)
>
> Why not just do it like that?  With a few changes it'll work fine:
>
> while q:
>     x = q.pop(0)
>     for y in process(x):
>         q.append(y)

Or (almost) equivalently...
while q:
    x = q.pop(0)
    q.extend(process(x))

--
Paul Hankin




More information about the Python-list mailing list