My understanding of this post on s/o
Iterators: An object whose items can be read one by one. Values stored in memory (can be expensive), and values are re-accessable
mylist = [x*x for x in range(3)]
Generators: are iterators, but can only be iterated only once, because data isn’t stored in memory, but created on the fly.
mygen = (x*x for x in range(3))
Yield: is like return, but the function will return a generator.
def genny(): mylist = range(3) for i in mylist: yield i*i
mygen = genny() for i in mygen: print i
Worth noting that the stuff written in the fn body does not run, and only returns the generator object. Every time a for loop calls the generator object created by the function, it will run the function until yield is hit. Every time it is called, the next iteration of the loop will be called, and value returned.