471,356 Members | 1,655 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,356 software developers and data experts.

Iterator for circulating a list

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
Nov 13 '07 #1
1 1128
"BJörn Lindqvist" <bj*****@gmail.comwrites:
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?
Nov 13 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

38 posts views Thread by Grant Edwards | last post: by
13 posts views Thread by Adam Hartshorne | last post: by
15 posts views Thread by sandwich_eater | last post: by
7 posts views Thread by andreas | last post: by
reply views Thread by mailforpr | last post: by
15 posts views Thread by jayesah | last post: by
12 posts views Thread by Howard | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.