Search code examples
pythonloopsgeneratorindex-error

Generator in Python, representing infinite stream


My code is as follows:

def infinite_loop():
    li = ['a', 'b', 'c']
    x = 0                           
   
    while True:
        yield li[x]
        if x > len(li):
           x = 0
        else:
           x += 1

I get a list index out of range error. What has gone wrong in my code?


Solution

  • The test is off by 2. The highest valid index is len(li) - 1, so after using that index, it needs to reset to 0:

    def infinite_loop():
        li = ['a', 'b', 'c']
        x = 0                           
       
        while True:
            yield li[x]
            if x == len(li) - 1:
               x = 0
            else:
               x += 1