0Pricing
Python Academy · Lesson

Generator Expressions

Write compact lazy pipelines.

From List Comp to Gen Expr

A generator expression looks like a list comprehension but uses parentheses instead of brackets. It produces values lazily instead of building a full list.

list_comp = [x * x for x in range(5)]
gen_expr = (x * x for x in range(5))
print(list_comp)
print(gen_expr)
print(list(gen_expr))

Memory Difference

A list comprehension allocates every element up front. A generator expression holds almost nothing until you ask for values. Compare their sizes.

import sys
lst = [x for x in range(10000)]
gen = (x for x in range(10000))
print('list bytes:', sys.getsizeof(lst))
print('gen bytes:', sys.getsizeof(gen))

All lessons in this course

  1. The Iterator Protocol
  2. Generator Functions
  3. Generator Expressions
  4. yield from and Delegation
← Back to Python Academy