Module 10 · Comprehensions and Advanced Iteration — topic 13 of 13
Lazy evaluation
Computing values only when they are needed: lazy built-ins (range, map, zip), generators and itertools, the memory and speed benefits, and the pitfalls of delayed execution.
Learning objectives
- Identify lazy and eager operations in Python
- Use laziness to save memory and time
- Avoid bugs caused by delayed execution
Definition
Lazy evaluation is a strategy where a value or sequence is computed only when it is actually needed, instead of eagerly in advance. In Python, ranges, iterators, generators and many itertools functions are lazy.
Introduction
range(10**12) is created instantly and uses almost no memory, because it doesn't store a trillion numbers — it computes each one when asked. That's lazy evaluation.
Why it matters
Laziness lets programs handle huge files, endless streams and expensive computations efficiently. It also changes when code runs, which can surprise you if you're not aware of it.
Detailed explanation
Eager operations compute everything immediately: list comprehensions, sorted(), list(), and most functions that return lists.
Lazy objects compute on demand: range, generator expressions, generator functions, map, filter, zip, enumerate, dict views and many itertools functions (islice, count, chain, takewhile).
Benefits: constant memory, the ability to stop early (any, all, next, islice), and infinite sequences.
Costs: values can be consumed only once (for iterators), len() and indexing are unavailable, and errors appear only when the bad item is reached — possibly far from where the generator was created.
Delayed execution also means a generator sees variables as they are when it runs, not when it was defined.
To 'freeze' a lazy result for repeated use, materialise it with list() or tuple().
Syntax
- range, map, zip, generators are lazy.
- list() forces evaluation.
- Errors surface when items are consumed.
Code examples
Huge but lazy
1000000000000 999999999999 True 0 1 4
Stopping early
[10, 15, 20, 25] [1, 2, 3, 4, 5, 6, 7]
More examples
When laziness bites
generator created failed later: invalid literal for int() with base 10: 'oops' | partial total: 30 [10, 20, 30] [10, 20, 30]
Step-by-step explanation
- Creating the generator doesn't convert anything, so the bad value causes no error yet.
- The error appears only when the loop reaches 'oops', after 10 and 20 were already added.
- scaled reads factor when it runs, after factor became 10 — so all values are multiplied by 10.
- The list comprehension is evaluated immediately, using the current factor (also 10 here).
Expected output
Running “When laziness bites” prints exactly:
Practical applications
- Streaming large CSV or log files.
- Paginating search results only as the user scrolls.
- Django querysets, which hit the database only when evaluated.
Best practices
- Use lazy tools for large or unbounded data.
- Materialise with list() when you need length, indexing or repeated passes.
- Validate input eagerly when early error reporting matters.
Common mistakes
Assuming errors happen at creation
Avoid
Prefer
Lazy operations defer work — and errors — until items are consumed.
Calling len() on lazy objects
Avoid
Prefer
Iterators don't know their length.
Important notes
- dict.keys(), values() and items() are lazy views that reflect later changes to the dictionary.
Key takeaways
- Lazy objects compute values only when requested.
- They save memory and allow early stopping and infinite sequences.
- Errors and variable lookups happen when items are consumed.
Try it yourself
- 1Find the first square number greater than 10,000 using count() and next().
- 2Show that changing a list after creating map(str, lst) affects the result.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?