Generator functions are coded as normal def statements, but use yield statements to return results one at a time,
suspending and resuming their state between each.
Generator expressions are similar to list comprehensions, but they return an object that produces results on demand instead of
building a result list.
The state that generator functions retain when they are suspended includes both their code location, and their entire local scope.
Hence, their local variables retain information between results, and make it available when the functions are resumed.
>>> def gensquares(N):
for i in range(N):
yield i ** 2 # Resume here later
>>> x = gensquares(4)
You get a generator object that supports the iteration protocol. The returned object has a __next__ method
that states the function and resumes it from where it last yielded a value, and raise a StopIteration exception when
the end of the series of values is reached and the function returns. next(X) built-in calls an objects X.__next__()
method for us.
>>> next(x)


雷达卡




京公网安备 11010802022788号







