Every for loop you've written uses the iterator protocol. Understanding it unlocks generators — a way to produce values lazily, one at a time, so you can process huge (even infinite) sequences without loading them into memory. This is the Pythonic path to fast, memory-light data code.
Iterables & iterators
An iterable is anything you can loop over (a list, string, dict, file). When you loop, Python calls iter() to get an iterator, then next() repeatedly until it raises StopIteration:
nums = [10, 20, 30]it = iter(nums) # get an iteratorprint(next(it)) # 10print(next(it)) # 20# ...until StopIteration# The for loop is just this, tidied up:for n in nums:print(n)
Generators & yield
A generator is a function that produces a series of values with yield instead of returning once. Each yield hands back a value and pauses the function, resuming where it left off on the next request. Values are computed on demand, so memory stays flat no matter how many there are:
def countdown(n):while n > 0:yield n # produce a value, then pausen -= 1for x in countdown(3):print(x) # 3, 2, 1# Lazy: this never builds a billion-element listdef naturals():n = 1while True: # infinite — but fine, it's lazyyield nn += 1
Generator expressions
A generator expression looks like a list comprehension with parentheses instead of brackets — same syntax, but lazy. Perfect as an argument to sum, max, any:
# List comprehension — builds the whole list in memorysquares = [n * n for n in range(1000)]# Generator expression — computes on demand, no list builttotal = sum(n * n for n in range(1_000_000)) # memory-lightany(s.placed for s in students)
Comprehensions
Comprehensions build a collection from an iterable in one readable line. They come in three flavours:
nums = [1, 2, 3, 4, 5]# List — transform + filterevens_sq = [n * n for n in nums if n % 2 == 0] # [4, 16]# Dict — build key/value pairslengths = {w: len(w) for w in ["excel", "sql"]} # {'excel': 5, 'sql': 3}# Set — unique resultsfirst_letters = {w[0] for w in ["sql", "scala", "python"]} # {'s', 'p'}
itertools
The standard-library itertools module is a toolbox of fast, lazy iterator building blocks:
from itertools import chain, groupby, count, islicelist(chain([1, 2], [3, 4])) # [1, 2, 3, 4] flattenlist(islice(count(1), 5)) # [1, 2, 3, 4, 5] take first 5 of infinite# groupby, product, combinations, accumulate… all lazy
Practice
Write a generator read_large(path) that yields a file's lines one at a time. Then use a generator expression to count how many lines contain the word "error" — without ever building a list of lines.
Key takeaways
- 01for loops use the iterator protocol: iter() then next() until StopIteration.
- 02A generator function uses yield to produce values lazily, one at a time — flat memory.
- 03Generator expressions are lazy comprehensions with () — ideal for sum/max/any over big data.
- 04List/dict/set comprehensions build collections in one readable line (one transform + one filter).
- 05itertools provides fast, lazy building blocks (chain, islice, groupby, product…).
