Generator in Python, representing infinite stream

827 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

When you try to access li[x] while x is equal or greater than the size of the list, it will throw OutOfRange exception.

    while True:
        # if x==3 this will throw error
        yield li[x]

        if x > len(li):
           x = 0
        else:
           x += 1

If you move yield after the if statement, the error will be gone

    while True:
        # if x==3, the following statement will assign 0 value to x
        # But you need to check with >= instead of >
        
        if x >= len(li):
           x = 0
        else:
           x += 1

        yield li[x]

But you can simplify it by using modulo operator (%)

    while True:
        yield li[x % len(li)]
        x += 1

Here's a working example: https://repl.it/@HarunYlmaz/python-generator