Generators Expressions in Python
A Python generator expression is a concise, memory-efficient, one-line syntax used to create iterator objects. They generate items on-demand (lazily) rather than storing the entire sequence in memory, making them ideal for large datasets.
Syntax
Generator expressions are similar to List comprehensions in Syntax (See Filtering and Reducing Lists in Python), with a small difference: generator expressions use parentheses instead of brackets or curly braces. The following example will produce a generator.
squares = (x * x for x in range(5)); # type: <class 'generator'> As you might expect, to get the full list of values, we can use the list() function. Although that will be equivalent to using a list comprehension.
squares = [x * x for x in range(5)]; # type: <class 'list'>
Lazy Evaluation
A generator expression computes values only when requested. As a generator expression returns an iterator object, it will not generate all values at once in memory, but instead produce them one by one during iteration. This behavior is known as lazy evaluation.
The built-in function next() is used to retrieve the next item from an iterator.
gen = (x * x for x in range(5))
print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 4