Lesson 9
No Object is an Island
Chapter 5: List comprehension
Generator expressions
Advanced topic! You can skip this if you prefer.
If you do not need the values of a list pre-stored in memory, you can use generator expressions instead of list comprehension. Syntax-wise, you just replace the square brackets with parentheses.
>>> generator = (number*number for number in range(100000))
>>> next(generator)
0
>>> next(generator)
1
>>> next(generator)
4
>>> next(generator)
9
Generator expressions are useful if you expect a list to be large and you need to conserve memory space.
One example usage would be to pass the generator to a function that is expecting an iterable object as an input argument (list, range, enumerate, zip are all iterables). You conserve some memory space compared to passing a list
.
>>> sum(number*number for number in range(100000))
Generator expressions can also be used as part of a for loop. The for loop will internally call next()
at the end of each iteration to dynamically receive the next item from the generator.
generator = (number*number for number in range(100000))
for number in generator:
if number % 3 == 0:
print(number)