Home » Learn Python » Iterators » Generator Expressions

Generator Expressions

We’ve seen list, set and dictionary comprehensions but we haven’t seen tuple comprehensions. That’s because there aren’t any tuple comprehensions in Python. The syntax that you might think would create one, actually creates an iterator.

This is known as a generator expression.

This code prints some square numbers.

gen = (x**2 for x in range(0, 10))

for i in gen:
    print(i, end=" ")

print() # Blank line
0 1 4 9 16 25 36 49 64 81

Leave a Reply

Blog at WordPress.com.

%d