10

In last week’s post we showed that a Python for-loop works through the Iterator Protocol.

This same protocol also enables values to be produced lazily.

In this new Lazy Evalution Example we show one sink reading values from five different sources:

  • source1: eagerly returns all values by list
  • source2: lazily by generator function using yield
  • source3: eagerly by list comprehension
  • source4: lazily by generator expression
  • source5: lazily by iterator protocol

The same for-loop consumes all five sources. The eager sources produce all values before the sink starts consuming them. In the lazy sources producer and consumer take turns:

  • produce → consume → produce → consume → …

Each value is produced only when the for-loop requests it.

Generator functions and generator expressions are concise, readable ways to create lazy iterables. The final source makes their underlying mechanism explicit:

  • iter() obtains an iterator.
  • next() requests the next value.
  • StopIteration signals that no values remain.

This clearly shows that generators achieve lazy iteration by implementing Python’s Iterator Protocol.

no comments (yet)
sorted by: hot top new old
there doesn't seem to be anything here
this post was submitted on 27 Aug 2026
10 points (100.0% liked)

Python

8019 readers
4 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 3 years ago
MODERATORS