Skip to content

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.

Beginner 10 min read·Lesson 157 of 306 in Python Programming

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

Python
big = range(10**12) # lazy, instant
squares = map(lambda x: x * x, big) # lazy
from itertools import islice, count, takewhile
first5 = list(islice(squares, 5)) # only 5 computed
  • range, map, zip, generators are lazy.
  • list() forces evaluation.
  • Errors surface when items are consumed.

Code examples

Huge but lazy

Python
big = range(10**12)
print(len(big), big[999_999_999_999])
print(10**12 - 1 in big)
squares = map(lambda x: x * x, big)
print(next(squares), next(squares), next(squares))
Output
1000000000000 999999999999
True
0 1 4

Stopping early

Python
from itertools import count, islice, takewhile
print(list(islice(count(10, 5), 4)))
print(list(takewhile(lambda n: n * n < 50, count(1))))
Output
[10, 15, 20, 25]
[1, 2, 3, 4, 5, 6, 7]

More examples

When laziness bites

Python
values = ["10", "20", "oops", "40"]
numbers = (int(v) for v in values) # no error yet
print("generator created")
total = 0
try:
for n in numbers:
total += n
except ValueError as e:
print("failed later:", e, "| partial total:", total)
factor = 2
scaled = (x * factor for x in [1, 2, 3])
factor = 10 # changed before the generator runs
print(list(scaled))
frozen = [x * factor for x in [1, 2, 3]]
print(frozen)
Output
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:

TextOutput
generator created
failed later: invalid literal for int() with base 10: 'oops' | partial total: 30
[10, 20, 30]
[10, 20, 30]

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

data = map(int, raw) # expecting validation here

Prefer

data = [int(x) for x in raw] # validate eagerly when you need errors up front

Lazy operations defer work — and errors — until items are consumed.

Calling len() on lazy objects

Avoid

len(map(str, items))

Prefer

len(items) # or len(list(...))

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

  1. 1
    Find the first square number greater than 10,000 using count() and next().
  2. 2
    Show 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?
Practise this topic