By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,551 Members | 1,142 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,551 IT Pros & Developers. It's quick & easy.

Iterator for circulating a list

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
"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.