Python: generator crash

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

This generator needs yieldall integers in rangeof (0, i), but it keeps returning 0on every call next(). What for?

Thank.

+4
source share
1 answer

No, it is not. This is the result:

>>> 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 to be expected. Each time you start from 0 and go to some one i, and then again return from 0 to the next value i.

+7
source

Source: https://habr.com/ru/post/1531618/


All Articles