
Python generators
What are they? How to use them?
#Python
Let's find out

Python generators are lazy iterators delivering the next value when their .next() is called.
They are created by using the yield keyword
next() can be called explicitly or implicitly inside for loop
They can be finite or infinite

yield - where a value is sent back to the caller, but the function doesnât exit afterward as with the return statement
The state of function is remembered.
For example, the number is incremented and sent back from yield at the consecutive call next()

Generator stores only the current state of the function - it generates next element on next() call and forgets the previous one -> it saves memory
For example, we don't need to store 1mio elements in memory to do something with each element

When you call a generator function generator object is returned - it's not executed yet
It executes only when next() is called
For example, that's why Exception is raised only on the next() call

When the generator goes out of elements it raises StopIteration exception

You can also create a class that behaves like a generator - it needs implemented methods:
- __iter__ -> to enable iteration
- __next__ -> to enable next element access

You can also create a generator with one-liner expression similar to list comprehension
Tip: mention @twtextapp on a Twitter thread with the keyword âunrollâ to get a link to it.