Generator
Generators are iterators, a kind of iterable you can only iterate over once.
Generators do not store all the values in memory, they generate the values on the fly:
Use ()
instead of []
. BUT, you cannot perform for i in mygenerator
a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.
Yield
yield
is a keyword that is used like return
, except the function will return a generator.