MCPcopy Create free account
hub / github.com/ActiveState/code / cycle

Function cycle

recipes/Python/578942_Cycling_a_sequence/recipe-578942.py:1–43  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

1def 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
45if __name__ == '__main__':
46 import doctest

Callers 8

rotationsFunction · 0.85
roundrobinFunction · 0.85
cycleMethod · 0.85
iterCombinationsFunction · 0.85
batch_sortFunction · 0.85
roundrobinFunction · 0.85
batch_sortFunction · 0.85
roundrobinFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected