cyclic iterators ?

Paul Rubin http
Fri Mar 2 20:27:29 EST 2007


"Tool69" <kibleur.christophe at gmail.com> writes:
> I've tried something like this to have a cyclic iterator without
> sucess:
> 
> def iterate_mylist(my_list):
>     k = len((my_list)
>     i=0
>     while i <= k :
>         yield my_list[i]
>         i += 1
>     i = 0
>     yield my_list[0]
> 
> I missed something, but I don't know what exactly.

As Bruno says, you can use itertools.cycle, but the problem above is
that you're not looping repeatedly through the list; you yield all the
elements, then yield the first element again, then stop.  So for
['a','b','c']  you'd yield the sequence a,b,c,a.  

I'd rewrite the above something like:

  def iterate_mylist(my_list):
     while True:
       for m in my_list:
          yield m

This just loops through the list over and over again.



More information about the Python-list mailing list