There is some technical distinction between the terms. An interator is something you can invoke
next
on, and a generator function or expression is something that returns an iterator. At least that much, I think I understand. So this first example is a simple generator function for the Fibonacci series:We use
islice
from itertools
to get a slice from it. This setup has the disadvantage that we are computing two values ahead of the one we actually return, but it allows me to do the yield in only one place.One great thing about iterators is that they allow you to deal with sequences that go on forever (like the Fibonacci sequence does) in a compact way. One can make a finite iterator like this:
The next example uses an "advanced" feature of iterators. It is possible to code it so that a value can be passed into the generator function by use of the
send
method. See here. In this contrived example, we simply advance the generator a given number of steps:The call to
send
does a yield thing.A more serious use of send is described by Alex Martelli here (in the first answer to the question).