List as FIFO in for loop

Carl Banks pavlovevidence at gmail.com
Sat Mar 8 23:42:31 CET 2008


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)


And consider collections.deque for q instead of a list, though it
shouldn't make much of a difference if the queue remains small.


Carl Banks



More information about the Python-list mailing list