The Iterator pattern decouples algorithms from containers;
First, the Iterator protocol- when you write.
Then remember that a generator is an Iterator;
Iterables are any objects you can get an Iterator from.
Here mylist is an iterable because it implements the Iterator protocol.
What makes an Iterator special is how it traverses a collection.
ERROR grunt. Grunt: ERROR 1066: Unable to open Iterator for alias.
When you request an Iterator from a list, it creates a new Iterator.
Also, you may want it to be recursive or generic, or to implement it as an Iterator.
A generator is exactly the same as any Iterator, except for the way it was written(with function syntax).
If an exception StopIteration is raised from within next(),
it means there are no more values in the Iterator and the loop is exited.
Loops do not necessarily require any special ordering of code for static branch prediction,
as only the condition of the loop Iterator is normally used.
Until you explicitly call return,
which will raise a StopIteration exception(which is also part of the Iterator protocol), or reach the end of the function.
I'm not particularly familiar with Python,
but I believe it's the same kind of thing as C 's Iterator blocks if you're familiar with those.
Other loops need to load the entire collection up front
in order to iterate over it, whereas an Iterator only needs to know the current position in the collection.
Whereas continuations are able in general to save the state of a computation(i.e., the program's call stack),
generators are only able to save the state of iteration over an Iterator.
Note that a for loop doesn't know what
kind of object it's dealing with- it just follows the Iterator protocol, and
is happy to get item after item as it calls next().