Iterator for circulating a list

BJörn Lindqvist bjourne at gmail.com
Tue Nov 13 09:12:31 EST 2007


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,'!'

Or maybe someone knows an even better way of expressing the above code?

-- 
mvh Björn



More information about the Python-list mailing list