A generator is a compact way of expressing a particular sequence of items as a function.
The most important aspects are:
The important part of a generator is the yield statement. Each time whatever is iterating over the generator asks for the next item in the sequence, the generator function is run up until the next yield statement is encountered, then the value provided to that statement is returned s the next item in the sequence. The key point to understand here is that after this, the generator function is 'paused' until the next time the generator gets asked for a new item. When an item is asked for again, the generator function resumes execution from exactly where it was previously, retaining the values that any variables local to the generator function had previously.
Further explanation will require some code, so here's an example:
last = 0 # Previous term
current = 1 # Current term
tmp = 0 # Temporary storage
tmp = last
last = current
current += tmp
This is a trivial generator function that will spit out the terms of the Fibonacci sequence. There's no termination condition, so if you were to loop over it, it the loop would just keep going forever.
Assume we start looping over this generator like so (don't do this unless you want to have to manually kill the Python interpreter, it will loop forever):
for x in fibonacci():
The overall execution flow will look like this:
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.