Generator Expressions
suggest changeGenerator expressions are very similar to list comprehensions. The main difference is that a generator expression does not build a full list of results at once; it creates a generator object which can then be iterated over.
For instance, see the difference in the following code:
# list comprehension
[x**2 for x in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# generator expression
(x**2 for x in range(10))
# Output: <generator object <genexpr> at 0x...>
These are two very different objects:
- the list comprehension returns a
listobject, whereas the generator expression returns agenerator. generatorobjects cannot be indexed. Use thenextfunction to get items in order. Indexing raisesTypeError. Callingnextafter the generator is exhausted raisesStopIteration.
squares = (x**2 for x in range(10))
squares[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable
squares = (x**2 for x in range(0))
next(squares)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Although both of these can be iterated in a similar way:
for i in [x**2 for x in range(10)]:
print(i)
"""
Out:
0
1
4
...
81
"""
Use cases
Generator expressions are lazily evaluated, which means that they generate and return each value only when the generator is iterated. This is often useful when iterating through large datasets, avoiding the need to create a duplicate of the dataset in memory:
for square in (x**2 for x in range(1000000)):
# do something
Another common use case is to avoid iterating over an entire iterable if doing so is not necessary. In this example, an item is retrieved from a remote API with each iteration of get_objects(). Thousands of objects may exist, must be retrieved one by one, and we only need to know if an object matching a pattern exists. A generator expression stops being pulled as soon as the function returns.
def get_objects():
"""Gets objects from an API one by one."""
while True:
yield get_next_item()
def object_matches_pattern(obj):
# perform a potentially complex calculation
return matches_pattern(obj)
def right_item_exists():
items = (object_matches_pattern(each) for each in get_objects())
for item in items:
if item:
return True
return False
get_next_item and matches_pattern stand in for the real API and test. Because get_objects never ends, right_item_exists returns True on the first match and otherwise loops forever; it does not reach return False.