Watch a generator in action:


Comprehension Generator

h = ( (i,i**2) for i in range(6) )
print type(h)
g = [ x for x in h ]
print type(g)
print g


Looking at the output when stepping through, we see that h is neither a tuple nor list, but instead h is a generator. Python prints something strange when asked to print h. Then, g is defined by a list comprehension, which treats h as a list. However, there is an unexpected twist when stepping through the program. To evaluate g, Python goes back to the generator (first line) multiple times, in order to construct the list.

So, generator h is a "delayed list" for purposes of later evaluation. The actual items of h are only created on demand (they would not be created at all if h were not used in any expression).