Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: generator fail

def sp():
    i = 0
    while True:
        for j in range(i):
            yield(j)
        i+=1

This generator is supposed to yield all the integers in the range of (0, i), but it keeps returning 0 with every call of next(). Why?

Thanks.

like image 816
AnnieOK Avatar asked Mar 21 '23 05:03

AnnieOK


1 Answers

No, it doesn't. This is the output:

>>> s=sp()
>>> s
<generator object sp at 0x102d1c690>
>>> s.next()
0
>>> s.next()
0
>>> s.next()
1
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
3
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
3
>>> s.next()
4

which is exactly what you would expect. Each time, you start from 0 and go to whatever i is, then start back from 0 again up to the next value of i.

like image 69
Daniel Roseman Avatar answered Mar 31 '23 21:03

Daniel Roseman