Python › Comprehensions & Generators
What is a generator expression, and how does it differ syntactically and behaviorally from a list comprehension?
IntermediateAnswer
A generator expression uses parentheses `(expr for item in iterable)` instead of square brackets, and produces a LAZY generator object (computing values one at a time on demand) rather than an eagerly-built list — using far less memory for large or infinite sequences since it never materializes the whole sequence.
sum_of_squares = sum(n * n for n in range(1_000_000)) # generator expression: no intermediate list built
# Wasteful alternative: builds a full 1,000,000-element list just to sum it
sum_of_squares2 = sum([n * n for n in range(1_000_000)])Real-world example Computing a sum, max, or any() result over a large sequence without ever materializing the full intermediate list in memory.