Yield keyword is used to define return of generator, replacing the return of a function to provide a
result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.
Generators
Generators are iterators, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly:
Yield
Yield is a keyword that is used like return, except the function will return a generator.\
Image Source- http://wla.berkeley.edu/
result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.
Generators
Generators are iterators, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly:
>>> pythonfaq_generator = (x*x for x in range(4))
>>> for i in pythonfaq_generator:
print(i)
0
1
4
9
Yield
Yield is a keyword that is used like return, except the function will return a generator.\
>>> def createGenerator():
... mylist = range(3)
... for i in mylist:
... yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
... print(i)
0
1
4
Image Source- http://wla.berkeley.edu/