Trouble understanding python generators -
this question has answer here:
- what “yield” keyword do? 33 answers
i new generator in python. have simple enough code playing can not understand output getting out of it. here code :
def do_gen(): in range(3): yield def incr_gen(y): return y + 1 def print_gen(x): in x: print x = do_gen() y = (incr_gen(i) in x) print_gen(x) print_gen(y)
i expected output :
0 1 2 1 2 3
but seeing : 0 1 2
i not understand output. can please me sort out lack of understanding? in advance.
generators (like iterables) can iterated on once. time print_gen(x)
done, x
. further attempts new values x
result in stopiteration
being raised.
this works:
x = do_gen() y = (incr_gen(i) in do_gen()) print_gen(x) print_gen(y)
as creates 2 separate independent generators. in version, generator expression assigned y
expects x
yield more values.
it easier see x
generator shared y
when use next()
function on them in turn:
>>> def do_gen(): ... in range(3): ... yield ... >>> def incr_gen(y): ... return y + 1 ... >>> x = do_gen() >>> y = (incr_gen(i) in x) >>> next(x) # first value range 0 >>> next(y) # second value range, plus 1 2 >>> next(x) # third value range 2 >>> next(y) # no more values available, generator done traceback (most recent call last): file "<stdin>", line 1, in <module> stopiteration
note stopiteration
raised next(y)
here.
Comments
Post a Comment