First page Back Continue Last page Overview Graphics

Generator Comprehension

They are simply like a list comprehension but with parentheses - round brackets - instead of (square) brackets around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a iterator instead of a list:

>>> x = (x **2 for x in range(20))

>>> print(x)

at 0xb7307aa4>

>>> x = list(x)

>>> print(x)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]