Search code examples
pythontuplesgenerator

Difference between generator expression and tuple expression


I have 2 statements

# Generator expression
squares_gen = (x**2 for x in range(10))
# Tuple comprehension
squares_tuple = (x**2 for x in range(10))

How does Python understand that the 1st statement is generator and the 2nd one is a tuple?

# Generator expression
squares_gen = (x**2 for x in range(10))

# Tuple comprehension
squares_tuple = (x**2 for x in range(10))

for square in squares_gen:
    print(square)

print(squares_tuple)

I am trying to understand how Python will process them differently


Solution

  • There is no such thing as a tuple comprehension. squares_tuple is still a generator.

    >>> squares_tuple = (x**2 for x in range(10))
    >>> type(squares_tuple)
    <class 'generator'>
    

    Because a generator is an iterable value, you can pass it to tuple to create a tuple.

    >>> tuple(squares_tuple)
    (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)