← Home ← Codex ← DEBT ← Engine
Browse by Category
+ added · updated 7d
← Back to glossary

Python Generators & yield

Python Python 2.2+ Intermediate
debt(d7/e2/b3/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7), because pylint/memray won't flag list-vs-generator choices automatically — memory issues typically surface in testing or review, not in static analysis.

e2 Effort Remediation debt — work required to fix once spotted

Closest to 'one-line patch' (e1) with slight bump toward e3 for cases needing function restructuring; quick_fix is literally swapping [...] for (...), but converting a return-list function to a yield-based generator may require small refactoring of call sites that index or re-iterate.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3), generators apply per-function and per-pipeline; the choice has modest reach (callers must know it's single-pass, not indexable) but doesn't shape system architecture.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap most devs eventually learn' (t5), matching the misconception that generators and lists are interchangeable — they cannot be restarted or indexed, and exhaustion raises StopIteration unexpectedly.

About DEBT scoring →

Also Known As

Python generators yield Python generator function

TL;DR

Functions that yield values one at a time — enabling lazy evaluation of infinite sequences without storing all values in memory.

Explanation

A generator function uses yield instead of return — calling it returns a generator object (an iterator). Each call to next() resumes execution until the next yield. Generators enable: memory-efficient processing of large files (yield line by line), infinite sequences (counter, Fibonacci), and pipeline composition (chain multiple generators). yield from delegates to another generator/iterable. Generator expressions (x*2 for x in items) are concise single-expression generators. send() passes values into a generator — forming the basis of Python coroutines (pre-async/await). PHP generators use the same yield keyword — a rare case where PHP and Python share nearly identical syntax and semantics. itertools provides composable generator utilities: chain, islice, groupby, product.

Common Misconception

Python generators and lists are interchangeable for iteration. Generators produce values lazily — each value is computed on demand. A generator processing 10 million records uses constant memory; building the same list exhausts memory. Generators cannot be restarted or indexed, unlike lists.

Why It Matters

Python generators produce values lazily with yield — they process one item at a time without loading everything into memory, essential for large files, streams, and infinite sequences.

Common Mistakes

  • Returning a list when a generator would be sufficient — materialises the entire sequence in memory.
  • Not using generator expressions: (x*2 for x in items) instead of list comprehensions for one-time iteration.
  • Calling next() without a default on an exhausted generator — raises StopIteration unexpectedly.
  • Generators that hold expensive resources without close() — use try/finally or contextlib.

Code Examples

✗ Vulnerable
# Loads entire file into memory:
def read_log(path):
    return open(path).readlines()  # 1GB log = 1GB RAM

# Generator — processes one line at a time:
def read_log(path):
    with open(path) as f:
        for line in f:
            yield line.strip()
✓ Fixed
def read_large_csv(path):
    with open(path) as f:
        next(f)  # skip header
        for line in f:
            yield line.strip().split(',')

# Processes millions of rows with constant memory
for row in read_large_csv('huge.csv'):
    process(row)

Added 15 Mar 2026
Edited 22 Mar 2026
Views 121
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 1 ping S 2 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 1 ping T 2 pings F 0 pings S 0 pings S 0 pings M
No pings yet today
No pings yesterday
Amazonbot 12 Scrapy 11 PetalBot 9 Ahrefs 8 SEMrush 8 Google 6 Perplexity 5 Brave Search 5 Bing 4 Unknown AI 3 Applebot 2 Claude 1 Sogou 1 Twitter/X 1
crawler 75 pre-tracking 1
🧱 FUNDAMENTALS — new to this? Start with the ground floor.
Python general Python is a programming language known for readable syntax and versatility, used for web development, data science, automation, and more.

Python's gentle learning curve makes it an ideal first language, while its vast ecosystem keeps it relevant for machine learning, APIs, and DevOps. Skills transfer directly to professional environments because Python runs in production at companies of every size.

💡 When Python throws IndentationError, check that every block uses the same whitespace style—pick spaces (preferably 4) and stick with them everywhere.

Ask Codex about Python →
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Low
⚡ Quick Fix
Replace list comprehensions that build large intermediate lists with generator expressions — swap [...] for (...) to get lazy evaluation
📦 Applies To
python 2.2 web cli
🔗 Prerequisites
🔍 Detection Hints
List comprehension loading entire dataset into memory before processing; returning large list from function that could yield
Auto-detectable: ✗ No pylint memray
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Function Tests: Update


✓ schema.org compliant