Iterator for circulating a list

Hrvoje Niksic hniksic at xemacs.org
Tue Nov 13 09:43:06 EST 2007


"BJörn Lindqvist" <bjourne at gmail.com> writes:

> L = somelist
>
> idx = 0
> while True:
>     item = L[idx]
>     # Do something with item
>     idx = (idx + 1) % len(L)
>
> wouldn't it be cool if there was an itertool like this:
>
> def circulate(L, begin = 0, step = 1):
>     idx = begin
>     while True:
>         yield L[idx]
>         idx = (idx  + step) % len(L)
>
> for x in circulate(range(10)):
>     print 'at', x,'!'

How about itertools.cycle?



More information about the Python-list mailing list