Search code examples
python-3.xlistgeneratoryield

when the generator stop for python?


I have python3 function like:

def previous_current(iterable):
    it = iter(iterable)
    prv = None
    cur = it.__next__()
    try:
        while True:
            yield prv,cur
            prv = cur
            cur = it.__next__()
    except StopIteration:
        yield prv, None

I find it the yield naturally stop, not execute except phase. like I invoke:

s1 = [1,2,3]
g = previous_current(s1)
for i in range(len(s1)):
    pre, cur = next(g)
    print(pre, cur)

it print:

None, 1
1, 2
2, 3

I just do not know I have while True condition, I think it will continue to run until error. But for this, it seems to stop when the list ends. I do not know why it runs like this. I think it should give result like:

None, 1
1, 2
2, 3  
3, None

Solution

  • @user504909 - this is because your range(len(s1)):
    So if you want to include 3, then as earlier post suggests you should change it to have it - range(len(s1)+1) then.

    The range() function has two sets of parameters, as follows:
    
    range(stop)
    
    stop: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) == [0, 1, 2].