List as FIFO in for loop

Arnaud Delobelle arnodel at googlemail.com
Mon Mar 10 23:10:03 CET 2008


On Mar 8, 2:43 pm, 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

You could make it safe this way ('emulating' what a listiterator
object does in CPython):

>>> from itertools import count
>>> def index_iter(l):
...     try:
...             for i in count(): yield l[i]
...     except IndexError:
...             return
...
>>> l = list('SPAM')
>>> for c in index_iter(l):
...     if c == 'A': l += list(' EGGS')
...     if c == 'S': l += list(' NI')
...
>>> ''.join(l)
'SPAM NI EGGS NI'
>>>

Of course in practice this is no different from doing 'for c in l:...'
but it is safe against implementation changes.

--
Arnaud




More information about the Python-list mailing list