Generator Expressions
Write compact lazy pipelines.
Generator Expressions is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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))Iterating a Gen Expr
You consume a generator expression like any iterator: with a for loop, next(), or by passing it to a function.
gen = (c.upper() for c in 'hello')
for ch in gen:
print(ch)Filtering With if
Add an if clause to keep only matching items, exactly like in a comprehension.
evens = (n for n in range(10) if n % 2 == 0)
print(list(evens))Passing Directly to Functions
When a generator expression is the only argument to a function, you can drop the extra parentheses. This is clean and avoids building a temporary list.
total = sum(x * x for x in range(5))
print(total)
biggest = max(len(w) for w in ['a', 'abc', 'ab'])
print(biggest)Single-Use Reminder
A generator expression is exhausted after one pass, just like a generator function. The second iteration yields nothing.
gen = (x for x in range(3))
print(list(gen))
print(list(gen))Chaining Expressions
You can feed one generator expression into another to build a lazy pipeline. Nothing is computed until the final consumer pulls values.
nums = (n for n in range(10))
evens = (n for n in nums if n % 2 == 0)
doubled = (n * 2 for n in evens)
print(list(doubled))any() and all()
Generator expressions shine with any() and all() because they can short-circuit, stopping as soon as the answer is known.
words = ['cat', 'dog', 'elephant']
print(any(len(w) > 5 for w in words))
print(all(len(w) >= 3 for w in words))Nested Loops
Like comprehensions, generator expressions support multiple for clauses, read left to right.
pairs = ((x, y) for x in range(2) for y in range(2))
print(list(pairs))Lazy Pipeline Example
Here is a small text-processing pipeline. Each stage is lazy, so a huge file could be streamed without loading it all.
lines = [' alpha ', '', ' beta', 'gamma ']
stripped = (line.strip() for line in lines)
nonempty = (line for line in stripped if line)
print(list(nonempty))When to Choose Which
Use a list comprehension when you need the data multiple times or need indexing. Use a generator expression for one-pass streaming or large data.
data = range(6)
as_list = [x + 1 for x in data]
print(as_list[0], as_list[-1])
total = sum(x + 1 for x in data)
print(total)Quick Check
Test your understanding of generator expressions.
Recap
You learned generator expressions:
- Use parentheses for a lazy alternative to list comprehensions.
- They save memory and support
iffilters and nested loops. - They pair well with
sum,any,all, and chaining. - They are single-use.
Next: composing generators with yield from.
Frequently asked questions
Is the “Generator Expressions” lesson free?
Yes — the full text of “Generator Expressions” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Generator Expressions”?
Write compact lazy pipelines. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Generator Expressions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Iterator Protocol
- Generator Functions
- Generator Expressions
- yield from and Delegation