List comprehension vs Generator Expression - lazy evaluation


The second big difference between list comprehension and generator expressions is that the latter has lazy evaluation. In this example you can see that once we assign to list comprehension to a variable the sqr function is called on each element.

In the case of the generator expression, only when we iterate over the elements will Python call the sqr function. If we exit from the loop before we go over all the values than we saved time by not executing the expression on every element up-front. If the computation is complex and if our list is long, this can have a substantial impact.


examples/generators/list_comprehension_generator.py
def sqr(n):
    print(f"sqr {n}")
    return n ** 2

numbers = [1, 3, 7]

# list comprehension
n1 = [ sqr(n) for n in numbers ]
print("we have the list")
for i in n1:
    print(i)
print("-------")

# generator expression
n2 = ( sqr(n) for n in numbers )
print("we have the generator")
for i in n2:
    print(i)

sqr 1
sqr 3
sqr 7
we have the list
1
9
49
-------
we have the generator
sqr 1
1
sqr 3
9
sqr 7
49