List as FIFO in for loop

rockingred willsteve2003 at yahoo.ca
Sat Mar 8 13:24:38 EST 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)
>
> 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?
>
> Regards,
>
> Muhammad Alkarouri

I think it's a bad practice to get into.  Did you intend to do the
"process" step again over the added variables?  If not I would set a
new variable, based on your awful naming convention, let's call it z.
Then use z.append(y) within the for loop and after you are out of your
for loop, q.append(z).



More information about the Python-list mailing list