A generator expression is very similar to list comprehension in Python. The advantage of the generator expression over list comprehension is that the resulting list of items is not actually created and filled in the former. Instead, the expression returns a generator object. On each call of the next() on this object, it returns the next item in the sequence. When the end of the sequence is reached, a StopIteration exception is thrown by next().
# List comprehension = [ i for i in range( 3 ) ] a # Generator expression = ( i for i in range( 3 ) ) b next( b ) # 0 next( b ) # 1 next( b ) # 2 next( b ) # StopIteration
A generator expression is useful to iterate through a very large or infinite sequence, since a list that large does not actually need to be created.
A generator object can be used in a for loop for iterating through its sequence easily without having to call next().
= ( i for i in range( 3 ) ) b for j in b: print( j ) # 0 1 2
Tried with: Python 3.2