Generator Expressions
Explore how to create and use generator expressions in Python to produce items lazily, improving memory efficiency. Understand the differences from list comprehensions, how to retrieve items from generators, and when to use inline generator expressions for concise code.
Generators can be easily created on the fly by using generator expressions.
Generator expression versus list comprehension
The syntax of a generator expression is similar to that of a list comprehension with just one difference: the square brackets are replaced by round parentheses. For example:
We can see that a generator expression doesn’t produce the output directly. It returns a generator object which will produce the items when explicitly told. Whereas, on printing listcomp, we immediately ...