Python for AI Engineers · Part A · Lesson 8 of 26
Python iterators and generators (and streaming LLM output)
Python iterators and generators for a Java or JavaScript developer: iter and next, what a for loop really does, yield, generator expressions, laziness and memory, lazy pipelines (read, clean, chunk), itertools (islice, chain, batched, groupby), yield from, and streaming LLM tokens into sentences.
⏱ 40 min3 exercises that check your codeRuns in your browser
By the end you can
- Tell an iterable from an iterator, drive one by hand with
iter()andnext(), and explain what aforloop does underneath - Write generator functions with
yieldand generator expressions, and know when they save memory - Chain generators into a lazy pipeline (read lines, clean, chunk) and use
itertools:islice,chain,batched,groupby - Delegate with
yield from, and turn a stream of LLM tokens into whole sentences with a generator
1Iterables, iterators, iter() and next()
Two words that sound alike and mean different things. An iterable is anything you can loop over: a list, a string, a dict, a file. An iterator is the cursor that walks over it, one item at a time, and remembers where it is. In Java terms: the list is the Iterable, and list.iterator() gives you the Iterator.
The built-in iter(x) asks an iterable for a fresh iterator (Java's iterator()). next(it) returns the next item (Java's next()). There is no hasNext(): when the items run out, next() raises StopIteration. Pass a second argument, next(it, default), and you get the default back instead of the exception.
A for loop is just that protocol written for you: it calls iter() once, calls next() until StopIteration, and swallows that final exception. The while loop at the bottom of the example is what for word in tokens: really runs.
tokens = ["Hello", "from", "Python"] # a list is an ITERABLE
it = iter(tokens) # ask it for an ITERATOR (a cursor)
print(next(it)) # each next() moves the cursor one step
print(next(it))
print(next(it))
print(next(it, "<no more>")) # a default instead of an error at the end
# What a for loop really does:
it = iter(tokens)
while True:
try:
word = next(it)
except StopIteration: # the iterator's way of saying "finished"
break
print("loop got", word)
Expected output
Hello from Python <no more> loop got Hello loop got from loop got Python
List<String> tokens = List.of("Hello", "from", "Python");
Iterator<String> it = tokens.iterator(); // iter(tokens)
while (it.hasNext()) { // Python has no hasNext():
String word = it.next(); // next() raises StopIteration instead
System.out.println("loop got " + word);
} const tokens = ["Hello", "from", "Python"];
const it = tokens[Symbol.iterator](); // iter(tokens)
let step = it.next(); // { value: "Hello", done: false }
while (!step.done) { // Python signals the end with an exception,
console.log("loop got", step.value); // not with a done flag
step = it.next();
} Tip Everything that works with a for loop also works with list(), sum(), max(), sorted(), "".join(), any() and all(). They all speak the same iterator protocol.
2Writing an iterator by hand (once)
Any class becomes an iterator with two special methods. __iter__ returns the iterator (for an iterator, that is itself). __next__ returns the next value, or raises StopIteration when it is done. These are the methods iter() and next() call.
You will rarely write this class in real code, because a generator (next section) does the same in a few lines. It is here so you can see the moving parts, and one important fact: an iterator only goes forward, and only once.
class Countdown:
"""An iterator written by hand: counts down from start to 1."""
def __init__(self, start):
self.current = start
def __iter__(self): # an iterator returns itself
return self
def __next__(self):
if self.current <= 0:
raise StopIteration # tell the for loop we are done
value = self.current
self.current -= 1
return value
for n in Countdown(3):
print(n)
c = Countdown(2)
print(list(c)) # list() runs the loop for you
print(list(c)) # used up: an iterator only goes forward, once
Expected output
3 2 1 [2, 1] []
Watch out A used-up iterator does not complain, it just looks empty. If a second loop over the same object prints nothing, you looped over an iterator (or generator) twice. A list can be looped over again and again because each for calls iter() and gets a new cursor.
3Generator functions: yield
A function that contains yield anywhere is a generator function. Calling it does not run its body: it returns a generator object, which is an iterator. Each next() runs the body until the next yield, hands that value back, and pauses right there with all its local variables kept. The next next() resumes on the line after the yield. When the body ends (or hits return), the generator raises StopIteration for you.
Watch the order of the printed lines: (starting) only appears at the first next(), not when countdown(2) is called. JavaScript has the same idea with function* and yield; Java has nothing built in (the closest is writing an Iterator class like the one above, or a Stream).
def countdown(start):
print(" (starting)")
while start > 0:
print(f" (about to yield {start})")
yield start # hand back a value and PAUSE here
start -= 1 # resumes here on the next next()
print(" (finished)") # falling off the end = StopIteration
gen = countdown(2) # nothing runs yet: you get a generator object
print(type(gen).__name__)
print(next(gen))
print(next(gen))
print(next(gen, "done"))
Expected output
generator (starting) (about to yield 2) 2 (about to yield 1) 1 (finished) done
function* countdown(start) { // the * marks a generator in JS
while (start > 0) {
yield start; // same keyword, same pause
start -= 1;
}
}
for (const n of countdown(3)) console.log(n); This short function replaces the whole Countdown class from the previous section: Python writes __iter__, __next__ and StopIteration for you, and the local variable start is the saved position.
4Generator expressions, laziness and memory
Swap the square brackets of a list comprehension for round ones and you get a generator expression: the same syntax, but it makes values on demand instead of building the whole list now. When it is the only argument of a call, you can drop the extra brackets: sum(n * n for n in nums).
That is what lazy means: no work happens until somebody asks for the next value. Two payoffs. Memory: the list below stores a million results at once, the generator stores only where it is. Early exit: next(...) on a generator expression gives you the first match and does not look at the rest.
The sizes are approximate: sys.getsizeof counts only the list's own slots (the integers inside take even more), and the numbers differ between Python versions and between your machine and the browser.
import sys squares_list = [n * n for n in range(1_000_000)] # builds all 1,000,000 values now squares_gen = (n * n for n in range(1_000_000)) # builds nothing yet print(sys.getsizeof(squares_list), "bytes for the list's slots") print(sys.getsizeof(squares_gen), "bytes for the generator") print(sum(squares_gen)) # values are made one at a time while sum() pulls them print(sum(squares_gen)) # 0: a generator expression is single-use too docs = ["hi", "ok", "a very long document", "yes", "another long document"] first_long = next(d for d in docs if len(d) > 10) # stops at the first match print(first_long)
Expected output
8448728 bytes for the list's slots 200 bytes for the generator 333332833333500000 0 a very long document
Tip Use a list when you need the values more than once, need len(), or need indexing. Use a generator when you go through the values once, especially when there are many of them or they come from a file, a database or a network.
5A lazy pipeline: read lines, clean, chunk
Generators shine when you chain them. Each stage takes an iterable, loops over it, and yields its own results. The next stage takes that generator as its input. Nothing runs until the final for loop asks for a chunk, and then each line flows through all three stages before the next line is read.
This is the first step of every RAG system: read documents, clean them, cut them into chunks small enough to embed. With generators a 5 GB file needs no more memory than a 5 KB one, because only one line (and one unfinished chunk) is in memory at a time.
io.StringIO makes a string behave like an open file, so the example runs in the browser. A real file object from open() is also an iterator of lines, so the same code works with with open("notes.txt", encoding="utf-8") as f: and chunk(clean(read_lines(f)), max_words=200).
import io
# A stand-in for open("notes.txt"): a file object is an iterator of lines too.
FILE = io.StringIO("""# team notes
Python generators are lazy.
They produce one value at a time.
# draft line, skip me
Pipelines pass items along one by one.
""")
def read_lines(f):
for line in f: # one line in memory at a time
print(f"read : {line!r}")
yield line
def clean(lines):
for line in lines:
line = line.strip()
if line and not line.startswith("#"): # drop blank lines and comments
yield line
def chunk(lines, max_words):
words = []
for line in lines:
words.extend(line.split())
while len(words) >= max_words:
yield " ".join(words[:max_words])
words = words[max_words:]
if words: # whatever is left at the end
yield " ".join(words)
pipeline = chunk(clean(read_lines(FILE)), max_words=6) # nothing has run yet
for piece in pipeline:
print(f"CHUNK: {piece}")
Expected output
read : '# team notes\n' read : 'Python generators are lazy.\n' read : '\n' read : 'They produce one value at a time.\n' CHUNK: Python generators are lazy. They produce read : '# draft line, skip me\n' read : 'Pipelines pass items along one by one.\n' CHUNK: one value at a time. Pipelines CHUNK: pass items along one by one.
Read the output in order. The first chunk is printed after only four lines were read: as soon as chunk had 6 words it yielded, and the for loop printed it before the file was read any further. {line!r} prints the line with repr(), which is why you see the \n at the end of each raw line and nothing hides in the blank one.
Watch out Do not return a generator from inside a with open(...) block and loop over it later. The with closes the file when the function returns, and the first next() then fails with ValueError: I/O operation on closed file. Either loop inside the with, or put the with inside the generator function itself.
6itertools: islice, chain, batched, groupby
The standard library module itertools has small, fast, lazy building blocks. Four you will use all the time:
islice(it, n) takes the first n items of any iterator (you cannot write gen[:3], because generators have no indexes). chain(a, b) loops over a and then b without copying them into one list. batched(it, n), new in Python 3.12, yields tuples of n items, and the last tuple may be shorter: exactly what you need to send texts to an embedding API in groups. groupby(it, key) groups neighbouring items that have the same key.
In the example, count(1) is an endless iterator (1, 2, 3, ...), which is safe only because islice stops pulling after a few items. The lambda c: c[0] is a one-line function that returns a chunk's file name, like c -> c[0] in Java or (c) => c[0] in JavaScript.
from itertools import batched, chain, count, groupby, islice
# islice: slicing for any iterator, even an endless one
ids = (f"doc-{n}" for n in count(1)) # count(1) = 1, 2, 3, ... forever
print(list(islice(ids, 3))) # take the first 3
print(list(islice(ids, 2))) # the next 2: the iterator remembers
# chain: several iterables, one after another, without copying them into one list
faq = ["What is RAG?", "What is a token?"]
docs = ("Intro to embeddings", "Chunking guide")
print(list(chain(faq, docs)))
# batched (new in Python 3.12): tuples of n items, the last one may be shorter
texts = ["a", "b", "c", "d", "e"]
for batch in batched(texts, 2):
print("embed batch:", batch)
# groupby: groups RUNS of neighbours with the same key, so sort by that key first
chunks = [("faq.md", 1), ("guide.md", 1), ("faq.md", 2), ("guide.md", 2)]
chunks.sort(key=lambda c: c[0])
for source, group in groupby(chunks, key=lambda c: c[0]):
print(source, [part for _, part in group])
Expected output
['doc-1', 'doc-2', 'doc-3']
['doc-4', 'doc-5']
['What is RAG?', 'What is a token?', 'Intro to embeddings', 'Chunking guide']
embed batch: ('a', 'b')
embed batch: ('c', 'd')
embed batch: ('e',)
faq.md [1, 2]
guide.md [1, 2]Tip batched exists only on Python 3.12 and later. On an older Python you will see ImportError: cannot import name 'batched'; the exercise at the end shows how to write it yourself.
Watch out groupby is not SQL GROUP BY. It only groups items that sit next to each other. Without the sort line you would get four groups (faq.md, guide.md, faq.md, guide.md) instead of two. Sort by the same key first, or collect into a dict when the data is not sorted.
7yield from: hand off to another generator
yield from other yields every item of other, one by one, as if you had written for x in other: yield x. Use it when a generator wants to pass along everything another generator (or any iterable) produces.
It reads well for "documents made of pages" and for recursion: flatten calls itself for each nested list and passes the results straight up to whoever is looping.
def pages(doc):
for i, text in enumerate(doc["pages"], start=1):
yield f'{doc["name"]} p{i}: {text}'
def all_pages(docs):
for doc in docs:
yield from pages(doc) # same as: for p in pages(doc): yield p
docs = [
{"name": "guide.pdf", "pages": ["Install", "Configure"]},
{"name": "faq.pdf", "pages": ["Pricing"]},
]
for page in all_pages(docs):
print(page)
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item) # recurse into nested lists
else:
yield item
print(list(flatten([1, [2, 3, [4]], [], 5])))
Expected output
guide.pdf p1: Install guide.pdf p2: Configure faq.pdf p1: Pricing [1, 2, 3, 4, 5]
enumerate(items, start=1) yields (number, item) pairs, so you get a counter without managing an index yourself. It is lazy too.
8Streaming LLM tokens with a generator
A model does not write its answer all at once. It produces a few characters (a token) at a time, and a streaming API sends each one as soon as it exists. In Python that stream is an iterator: you loop over it and get pieces of text. Showing them as they arrive makes a slow answer feel fast.
Below, fake_token_stream pretends to be the model by yielding 4 characters at a time. The sentences generator sits between the stream and your app: it collects tokens and yields only whole sentences. You need that when you send speech to a text-to-speech engine, or check each sentence before showing it. Both are generators, so the first sentence comes out while the "model" is still writing the rest.
print(token, end="|") prints without a newline (end replaces the default "\n"), so you can see where each token starts and ends. In a terminal, write print(token, end="", flush=True) for the live typing effect: flush=True pushes the text to the screen right away instead of waiting for a full line.
import time
def fake_token_stream(text, delay=0.0):
"""Pretend to be a model: yield the answer a few characters at a time."""
for i in range(0, len(text), 4):
time.sleep(delay) # a real model takes tens of milliseconds per token
yield text[i:i + 4]
def sentences(tokens):
"""Collect tokens into whole sentences (for text-to-speech, or a tidy UI)."""
buffer = ""
for token in tokens:
for ch in token:
buffer += ch
if ch in ".!?": # a sentence just ended
yield buffer.strip()
buffer = ""
if buffer.strip(): # the stream ended in the middle of a sentence
yield buffer.strip()
answer = "DNS maps names to IP addresses. It works like a phone book! Want an example"
for token in fake_token_stream(answer):
print(token, end="|") # show where each token starts and ends
print()
for n, sentence in enumerate(sentences(fake_token_stream(answer)), start=1):
print(n, sentence)
Expected output
DNS |maps| nam|es t|o IP| add|ress|es. |It w|orks| lik|e a |phon|e bo|ok! |Want| an |exam|ple| 1 DNS maps names to IP addresses. 2 It works like a phone book! 3 Want an example
Notice that the sentence boundary falls inside tokens ("es. " holds the end of one sentence and the space before the next), which is why sentences looks at every character, not at whole tokens. This simple rule also splits 3.5 and e.g.; production code uses a smarter sentence splitter, but the generator shape stays the same.
Tip Set delay=0.05 and run the first loop in a terminal with end="", flush=True to watch the answer type itself out.
9The real thing: streaming from the OpenAI SDK
With the openai SDK (the one from lab 1, pointed at your local Ollama), stream=True turns the response into an iterator of chunks. Each chunk carries a small piece of new text in chunk.choices[0].delta.content. Wrap that loop in your own generator and the rest of your code sees a plain stream of strings, exactly like fake_token_stream above, so sentences() works on it unchanged.
This runs on your machine, not in the browser (the browser cannot reach your Ollama). You need Ollama running with llama3.2:3b pulled, as in lab 1. Save the file as stream_demo.py and run the command below.
uv run --with "openai>=1.50" stream_demo.py DNS (Domain Name System) translates human-friendly domain names into the IP addresses computers use. It works like a phone book for the internet.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
def stream_answer(question):
"""Yield the model's answer piece by piece, as it is generated."""
stream = client.chat.completions.create(
model="llama3.2:3b",
messages=[{"role": "user", "content": question}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
for token in stream_answer("What is DNS? Answer in two sentences."):
print(token, end="", flush=True)
print() - Ollama speaks the OpenAI API at
/v1. It ignores the key, but the SDK insists on one, so any string works.line 3 - A generator function: calling
stream_answer(...)sends nothing yet. The request goes out on the firstnext(), when theforloop at the bottom starts.line 6 stream=Truemakes the SDK return an iterator of chunks instead of one finished response.line 11- Each
chunkis one server-sent event. The loop waits for the next one to arrive over the network.line 13 - The first and last chunks usually carry no text (
contentis""orNone), and a final usage chunk can have an emptychoiceslist, so we skip those.line 14 - Yield only the new text. Callers never see SDK objects, so they cannot tell this from the fake stream (handy for tests).line 15
- Print each piece the moment it arrives, without a newline, and flush so it shows up immediately.line 19
The answer is written by the model, so your words will differ; what matters is that it appears piece by piece. uv run --with installs openai into a temporary environment just for this run. To get sentences instead of tokens, loop over sentences(stream_answer(...)) with the sentences function from the previous section. The streaming chat lab sends this same generator to a browser.
Tip Keep the full text too: collect the pieces in a list and "".join(parts) at the end, so you can save the answer to the chat history and log it.
Common mistakes
- Looping over the same generator twice. The second loop silently gets nothing. Turn it into a list (
items = list(gen)) if you need it more than once, or call the generator function again. - Calling a generator function and expecting it to run:
countdown(3)alone does nothing, not even its firstprint. Something has to loop over it. - Using
groupbyon unsorted data and getting the same key in several groups. Sort by the key first. - Returning a generator from inside a
with open(...)block. The file is closed before anyone reads it. Keep the loop inside thewith. - Trying
len(gen)orgen[0]on a generator. Generators have no length and no indexes; usenext(gen),islice, orlist(gen)when the data is small.
Practice
Write the code, then press Check. Your work is saved in this browser.
1A cleaning generator
Rewrite clean_lines as a generator function: for each input line, strip the spaces and newline around it, skip it if it is empty or starts with #, and yield the rest. It must not build a list.
def clean_lines(lines):
result = []
for line in lines:
line = line.strip()
if line and not line.startswith("#"):
result.append(line)
return result
print(list(clean_lines([" hello \n", "\n", "# comment", "world"])))
Hint
Replace `result.append(line)` with `yield line`, and delete the `result` list and the `return`.
2Tokens into sentences
Finish the generator sentences(tokens). It receives pieces of text from a stream and yields each whole sentence, stripped of surrounding spaces, as soon as a ., ! or ? arrives. When the stream ends, yield the leftover text if it is not blank. A sentence end can be in the middle of a token.
def sentences(tokens):
buffer = ""
for token in tokens:
buffer += token
# yield a sentence each time one ends with . ! or ?
yield buffer
print(list(sentences(["Hi", " there.", " Bye", "!"])))
Hint
Loop over every character of each token. Add it to the buffer; if it is one of `.!?`, yield `buffer.strip()` and reset the buffer. After the loop, yield `buffer.strip()` only if it is not empty.
3Write your own batched
Write a generator my_batched(iterable, n) that works like itertools.batched on any Python: it yields tuples of n items, and a shorter last tuple if items are left over. It must be lazy: to produce the first batch it may pull only n items from its input.
def my_batched(iterable, n):
# your code here
yield tuple(iterable)
print(list(my_batched("abcde", 2)))
Hint
Keep a list `batch`. Append each item; when `len(batch) == n`, yield `tuple(batch)` and start a new empty list. After the loop, yield what is left if the list is not empty.
Interview questions
Q1What is the difference between an iterable and an iterator?
An iterable is something you can loop over (it has __iter__, so iter(x) works): lists, strings, dicts, files. An iterator is the cursor that produces the items: it has __next__, remembers its position, goes forward only, and is used up after one pass. iter(iterable) gives a fresh iterator; an iterator's iter() returns itself.
Q2How does a for loop work in Python?
It calls iter() on the object once, then calls next() on the iterator repeatedly, running the body for each value, until next() raises StopIteration, which the loop catches and treats as the normal end.
Q3What is a generator and how is it different from a normal function?
A function containing yield. Calling it returns a generator object without running the body. Each next() runs the body to the next yield, returns that value and pauses with its local state saved. It is a compact way to write an iterator, and it computes values lazily.
Q4When would you use a generator instead of a list?
When the data is large or unbounded (big files, database rows, a network stream), when you only need one pass, or when you may stop early. A generator keeps one item in memory at a time. Use a list when you need len(), indexing, or several passes.
Q5What does yield from do?
yield from it yields every value of another iterable or generator in turn, like for x in it: yield x. It is used to delegate to sub-generators and for recursive generators. (It also passes values sent with send() through and returns the sub-generator's return value.)
Q6How would you stream an LLM response in Python?
Call the API with stream=True and loop over the returned iterator of chunks, taking delta.content from each and skipping empty ones. Wrap that loop in a generator that yields plain strings, so the UI, a sentence splitter or a test fake can consume it the same way. Also join the pieces at the end to keep the full answer for history and logs.