Yu Shen
Yu Shen

Reputation: 2910

How to implement "circular" generator in Python?

Given a generator expression:

a = (x for x in range(3)) 
print(next(a)) # 0 
print(next(a)) # 1 
print(next(a)) # 2 
print(next(a)) # StopIteration 
exception 0 1 2 
--------------------------------------------------------------------------- StopIteration                             
Traceback (most recent call last) 
<ipython-input-40-863a9b3464a7> in <module>()       
3 print(next(a))       
4 print(next(a)) 
----> 5 print(next(a))  

StopIteration:

How can I implement a generator, when the "StopIteration exception" would happen, then it "rewind" to the beginning, returns 0 again?

Upvotes: 0

Views: 225

Answers (1)

Lafexlos
Lafexlos

Reputation: 7735

You can use itertools.cycle(iterable) method for this.

It takes an iterable as parameter and cycles through its items.

>>>cycle('ABCD') --> A B C D A B C D A B C D 

Upvotes: 3

Related Questions