Generators and lazy evaluation
A generator hands you results one at a time instead of building a whole list first. That one idea lets a laptop work through files far bigger than its memory. This lesson starts from a plain function and changes one word.
Foundations · Python for data engineers · Silver · Functions and laziness, lesson 2 of 3
On this page
Read first: Comprehensions (skip if you know it)
In plain words first
Picture a kitchen with two cooks and an order for three dishes:
return: all at once
yield: one at a time
In code the difference is one word. The first function builds a list and returns it. The second has yield where the first had append, and gives the same numbers one by one:
def all_at_once(n): result = [] for i in range(1, n + 1): result.append(i * 10) return result def one_at_a_time(n): for i in range(1, n + 1): yield i * 10 print(all_at_once(3)) print(list(one_at_a_time(3))) for amount in one_at_a_time(3): print("got", amount)
Output from a real run
[10, 20, 30] [10, 20, 30] got 10 got 20 got 30
A for loop (or list()) asks the generator for values until it runs out. The difference is invisible here, with three numbers. It matters when there are millions of them, or when they never end, as the sections below show.
A function that pauses
A function that contains yield is a generator function. Calling it runs none of its body: it only gives you a generator object, ready to start. Each next() runs the body until the next yield, hands that value out, and pauses there with all its variables kept. Click through what happens:
Step 1 · call it
countdown(3) runs nothing yet. It returns a paused generator; "starting" is not printed.The command
gen = countdown(3)
Step 2 · first next()
yield n. It hands out 3 and pauses right there, with n = 3 remembered.The command
next(gen) # 3
Step 3 · second next()
yield, runs n -= 1, goes round the loop and yields 2. Then it pauses again.The command
next(gen) # 2
Step 4 · the rest
list(gen) keeps asking: it gets 1, then the loop ends and the function finishes. Finishing raises StopIteration, which tells list to stop.The command
list(gen) # [1]
The same steps as code you can run:
def countdown(n): print("starting") while n > 0: yield n n -= 1 gen = countdown(3) print("created") print("first next:", next(gen)) print("second next:", next(gen)) print("what is left:", list(gen))
Output from a real run
created starting first next: 3 second next: 2 what is left: [1]
Constant memory, any size of input
Because a generator produces one item at a time, a loop over it holds one item, not the whole data set. That is how you process a 50 GB log on a laptop, read a paginated API, or work on a stream that never ends.
The example below uses a generator expression: a list comprehensioncomprehension: A one-line way to build a list, set or dict from another iterable, like [x * 2 for x in xs if x > 0]. Learn more → with round brackets instead of square ones. [n * n for n in ...] builds the whole list now; (n * n for n in ...) builds a generator that works each value out only when asked.
import sys as_list = [n * n for n in range(1_000_000)] as_gen = (n * n for n in range(1_000_000)) print("list over 1 MB:", sys.getsizeof(as_list) > 1_000_000) print("generator under 1 KB:", sys.getsizeof(as_gen) < 1_000) print("same total:", sum(as_gen) == sum(as_list))
Output from a real run
list over 1 MB: True generator under 1 KB: True same total: True
Pipelines of small generators
Each stage takes an iterableiterable: Anything you can loop over with for: a list, a string, a dict, a range, a file. Calling iter() on it gives a fresh iterator. Learn more → and yields results, so stages chain like an assembly line. One record flows through every stage before the next is read. Each stage stays small and testable, and nothing is held in memory between them.
You can watch the order things happen in. Each stage prints what it does:
def numbers(): for n in [1, 2, 3]: print("read", n) yield n def doubled(items): for n in items: print(" double", n) yield n * 2 for x in doubled(numbers()): print(" use", x)
Output from a real run
read 1
double 1
use 2
read 2
double 2
use 4
read 3
double 3
use 6With lists, all three "read" lines would print first, then all three "double" lines. With generators, the number 1 is read, doubled and used before 2 is even read. Here is a more realistic line: read lines of text, parse them, keep the late deliveries.
-
read_lines
one line of text
-
parse
id and minutes
-
late
only slow ones
def read_lines(text): for line in text.splitlines(): yield line def parse(lines): for line in lines: order_id, minutes = line.split(",") yield order_id, int(minutes) def late(orders, limit): for order_id, minutes in orders: if minutes > limit: yield order_id feed = "o1,25\no2,48\no3,31\no4,52" print(list(late(parse(read_lines(feed)), 40)))
Output from a real run
['o2', 'o4']
Endless inputs and taking only what you need
A generator may never end. itertools.islice(gen, n) takes the first n items; next(gen) takes one. Anything that tries to consume the whole input (list(), sorted(), len()) never returns on an endless one, which is a quick way to tell whether code is really lazy.
import itertools def order_ids(): n = 1 while True: yield f"o{n}" n += 1 print(list(itertools.islice(order_ids(), 3)))
Output from a real run
['o1', 'o2', 'o3']
One pass only
A generator is used up after one pass: a second loop over it sees nothing. If you need the data twice, or need its length, random access or sorting, build a list (when it fits in memory) or create the generator again.
squares = (n * n for n in range(3)) print("first pass:", list(squares)) print("second pass:", list(squares))
Output from a real run
first pass: [0, 1, 4] second pass: []
Generator or list?
| Use a generator when... | Use a list when... |
|---|---|
| The data is big, or you do not know how big | The data is small and fits in memory easily |
| You read it once, from start to end | You need it twice, or need len(), indexing or sorting |
| The input may never end (a stream, a paginated API) | You want to print or inspect all of it while debugging |
| You chain steps: read → clean → filter | A function must return a finished result to its caller |
Common mistakes
- Calling list() on a stream "to make it easier" — It loads everything, or never returns. Keep stages lazy.
- Looping over the same generator twice — The second loop is empty. Recreate it or store a list.
- Expecting errors at call time — The body (and its validation) runs on the first next(), not when the function is called.
Key takeaways
- return hands over everything at the end; yield hands over one value and pauses.
- A function with yield returns a generator; its body runs on next().
- Generators hold one item at a time: constant memory.
- Chain small generators into pipelines: each item goes through every step before the next is read.
- They are one-pass; islice takes a prefix of an endless one.
Interview prep
THE QUESTION
"How would you process a 50 GB log file in Python on an 8 GB machine?"
Avoid: "a generator is a faster list". It is lazy and one-pass; it saves memory, not necessarily time.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between return and yield in a function?"
Scenario"An API returns results in pages of 100. Give callers a simple way to iterate over every result."
Trap"A generator function that raises ValueError for bad arguments fails as soon as it is called."
Check yourself
4 questionsWhat does (n * 2 for n in nums) create?
Show the answer
A generator. Round brackets around a comprehension make a generator expression.
When does the first line of a generator function's body run?
Show the answer
On the first next(). Calling it only creates the generator.
Which never returns on an endless generator?
Show the answer
list(g). list tries to consume everything.
g = (x for x in [1, 2]); list(g); list(g) gives...
Show the answer
[1, 2] then []. A generator is exhausted after one pass.
Practise this
Problems that use this, graded on hidden tests
- Read a File in ChunksGenerators & iterators Easy
- Batch an IterableGenerators & iterators Easy
- Moving Average over a StreamGenerators & iterators Medium
Keep going
Up next · Functions and laziness · lesson 3 of 3 · 8 min readIterators, yield from and itertools
The iterator protocol, re-iterable classes, recursive generators and the itertools you will use.
Related lessons
Previous: Decorators
Primary sources: Generators (tutorial) · itertools