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'
(seq)
| 1 | def cycle(seq): |
| 2 | """Return a generator producing items from seq. When seq is |
| 3 | exhausted, the generator will cycle over from item 0 again. |
| 4 | |
| 5 | Beware that a break statement is necessary in a for loop. Also, seq |
| 6 | is a sequence supporting the len function and enumerated 0-based. |
| 7 | |
| 8 | Examples: |
| 9 | |
| 10 | >>> seq = ['one', 'two', 'three'] |
| 11 | >>> cyc = cycle(seq) |
| 12 | >>> next(cyc) |
| 13 | 'one' |
| 14 | >>> next(cyc) |
| 15 | 'two' |
| 16 | >>> next(cyc) |
| 17 | 'three' |
| 18 | >>> next(cyc) |
| 19 | 'one' |
| 20 | >>> next(cyc) |
| 21 | 'two' |
| 22 | |
| 23 | To reset, call for a new cycle: |
| 24 | |
| 25 | >>> cyc = cycle(seq) |
| 26 | >>> next(cyc) |
| 27 | 'one' |
| 28 | >>> for i, item in enumerate(cyc): |
| 29 | ... print i, item |
| 30 | ... if i > 3: |
| 31 | ... break # Must break out manually |
| 32 | ... |
| 33 | 0 two |
| 34 | 1 three |
| 35 | 2 one |
| 36 | 3 two |
| 37 | 4 three |
| 38 | |
| 39 | """ |
| 40 | i = 0 |
| 41 | while True: # Cycle forever |
| 42 | yield seq[i] |
| 43 | i = (i + 1) % len(seq) |
| 44 | |
| 45 | if __name__ == '__main__': |
| 46 | import doctest |
no outgoing calls
no test coverage detected