Dean
Dean

Reputation: 31

Why is the generator infinite?

Please take a look at this generator of generators (written in Python):

def gen_chars():
    def gen_row(j):
        while True: yield from j

    for l in ['1234', 'abc', 'ABC', '0']: yield gen_row(l)

What I don't understand is:

Why any of these four generators is infinite?

For example: Why the first generator is: 1, 2, 3, 4, 1, 2, 3, 4, 1, ... (the loop never ends),

and not just: 1, 2, 3, 4 (end)?

Thanks in advance for your help!

Upvotes: 0

Views: 641

Answers (3)

Grismar
Grismar

Reputation: 31319

Consider this simpler example:

def g():
    yield from '1234'


def h():
    while True:
        yield from '1234'


for x in g():
    print(x)

for x in h():
    print(x)

What do you expect to happen during the first for loop? It appears, from your question, that you might expect it to yield '1234' in one go. Or perhaps you expect what actually happens, it yields '1', '2', etc.

yield from some iterable yields one value at a time.

If that makes sense, it should also make sense that the generator h() will yield the same characters one at a time, but once that's done, the while True: will cause it do that again and again, forever.

This is what happens in the first generator yielded by your generator generator and since that's the first generator you start drawing from, you're stuck getting values from it forever.

Upvotes: 1

Nathan Roberts
Nathan Roberts

Reputation: 838

while True will always cause an infinite loop unless you break out of it at some point. If you are trying to yield each individual character from each item in the list then you should do something like this:

def gen_chars():
   def gen_row(j):
      for c in j:
         yield c

   for l in ['1234', 'abc', 'ABC', '0']: yield gen_row(l)

Upvotes: 1

Kesslwovv
Kesslwovv

Reputation: 652

it loops infinitely because you have a while True in your gen_row and no condition to exit it. so this will loop and yield forever from j, in this case '1234', because it was the first time ever, this function was called.

Upvotes: 2

Related Questions