Search code examples
pythongeneratorinfinite-sequence

Print an infinite sequence using generator


I'm trying to create a generator that prints out a specified infinite sequence. Currently, I have the following code:

def numGen():
for i in range(1,13):
    yield i

Which then gives me:

>>> y = numGen()
>>> y
<generator object numGen at 0x7f6b88d22570>
>>> y.__next__()
1
...
>>> y.__next__()
12
>>> y.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module> StopIteration

I'm not sure what would need to be changed in order for it to reset and then print out 1, 2, 3, ..., 11, 12, 1, 2, 3,... I've tried adding the line "i += 1" after the yield line, but it would then print out 14 which isn't what I want.


Solution

  • The core problem with the shown generator is it only loops the sequence once - and then it stops. A simple change would be to wrap it in an outer while True, eg.:

    def numGenForever():
        while True:
            for i in range(1,13):
               yield i
    

    This would then be "infinite" because it would restart the sequence iteration after each previous completion.