May 2019
Beginner
528 pages
29h 51m
English
A generator expression is similar to a list comprehension, but creates an iterable generator object that produces values on demand. This is known as lazy evaluation. List comprehensions use greedy evaluation—they create lists immediately when you execute them. For large numbers of items, creating a list can take substantial memory and time. So generator expressions can reduce your program’s memory consumption and improve performance if the whole list is not needed at once.
Generator expressions have the same capabilities as list comprehensions, but you define them in parentheses instead of square brackets. The generator expression in snippet [2] squares and returns only the odd values in numbers:
In [1]: numbers ...Read now
Unlock full access