A post-it function to cycle through some sequence. Better use itertools.cycle if for any iterable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | def cycle(seq):
"""Return a generator producing items from seq. When seq is
exhausted, the generator will cycle over from item 0 again.
Beware that a break statement is necessary in a for loop. Also, seq
is a sequence supporting the len function and enumerated 0-based.
Examples:
>>> seq = ['one', 'two', 'three']
>>> cyc = cycle(seq)
>>> next(cyc)
'one'
>>> next(cyc)
'two'
>>> next(cyc)
'three'
>>> next(cyc)
'one'
>>> next(cyc)
'two'
To reset, call for a new cycle:
>>> cyc = cycle(seq)
>>> next(cyc)
'one'
>>> for i, item in enumerate(cyc):
... print i, item
... if i > 3:
... break # Must break out manually
...
0 two
1 three
2 one
3 two
4 three
"""
i = 0
while True: # Cycle forever
yield seq[i]
i = (i + 1) % len(seq)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
This solution could possibly be of interest if any worries for, as the documentation for itertools.cycle say, "significant auxiliary storage". This way no extra memory is used I guess.
Also, as usual when I write something, I realize afterward that the solution is already out there.