What is generator in Python?
- A simple way of creating iterators
- A function with
yieldstatement instead of
returnstatement. It can have mutilple
- Iterator methods
__next__()are implemented automatically.
yieldstatement pauses the function saving all its states and later continues from there on successive calls.
- When called, it returns an object (iterator) but does not start execution immediately.
- Easy to implement. No need to warry about methods
- Memory efficient
- Represent infinite stream
- Pipling generator
[x for x in range(5)] ==> list
(x for x in range(5)) ==> generator
tuple(range(5)) ==> tuple
Written on May 10, 2019