Generators
Generators
Collections vs Generators
->
Collections vs Generators
->
Limitation
-> it won’t store data.
-> We cannot ask a particular element.
Def factorial(n):
for i in range(n):
emit factorial(i)
pause execution here
wait for resume
return ‘done!’
And in our code we want to do something like this maybe
-> facts = factorials(4)
-> We create an instance of factorials, so calling an function does
not do an iteration, it just create an some object.
-> and maybe we call something like give the next factorial.
get_next(0)!
get_next(1)!
Def song():
print(‘line 1’)
yield “I am a lumberjack and I’m ok”
print(‘line 2’)
yield “I sleep all night and I work all day”
Def factorials(n)
for i in range(n):
yield math.factorial(i)
fact_iter = factorials(5)
Generator functions which contain atleast one yield statement.
Generators are iterators, and can be used in the same way (for
loops, comprehensions) etc.