Generators
Generator is non-exiting function that stores it's state in memory and can return result values many times when called.
Generator is the result of generator function
Generators function looks like regular function but instead of return
they use yield
which will return provided value and "freeze" generator state. Next time generator is called it will be resumed from the next statement after yield
.
After creation of generator we can call it's __next__()
method to get next value (next()
for Python2). If no items will be available (function will end) StopIteration
exception will be thrown to indicate this.
So, function
is a "generator function
" if it has yield
statement.
The result of generator function
is called generator
.
Generator is specific kind of object that has __next__
method which returns "next" value until raising StopIteration
exception meaning that it is the end of data.
Generator is particular case of more generic type - "iterator" which is defined as object with __next__
and __iter__
methods.
🪄 Code:
📟 Output:
Generator expressions
Very similar to list comprehension. Instead of sqaure brackets []
for generator expressions it's needed to use parentheses ()
.
Important thing to understand - generator is the result of calling generator function or the result of running generator expression
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Last updated