+ -

Pages

Friday, May 4, 2012

Generators

Generators are merely functions that use yield instead of return. Also, the retain the state of all the local variables between calls.


def gen(n):
i=0
while i<n:
yield i*i
i+=1

to use it, apply the function next() as in:
 next(gen(100))

to retain the state, you have to assign the generator to a variable then use next on it (or it will start over):

g=gen(100)
next(g)
0
next(g)
1
next(g)
4
5 Khalid's Python Journal: Generators Generators are merely functions that use yield instead of return. Also, the retain the state of all the local variables between calls. d...

No comments:

Post a Comment

< >