Python Generators and yield
PCEP names generators in passing under objective 4.1 and asks little about them; PCAP's comprehension and closure material assumes you know what a lazy sequence is. This guide fills that gap. A generator is a function containing yield: calling it runs none of the body, and each next() runs it as far as the next yield and then freezes it there. Seeing that interleaving is the only way it becomes obvious.
Functions and Scope Guide 22 of 26 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 14 min
yield has been in Python since 2.2 and generator expressions since 2.4. Nothing here is version-sensitive. yield from and send() exist and are examined by neither exam.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for the generator material PCEP names in passing and PCAP tests properly. This matters because a generator produces nothing until asked and can be walked only once - so whatever consumes it second gets an empty sequence.
- turning a function into a generator with
yield - seeing what happens when a generator runs off the end
- using one anywhere an iterable is accepted
- finding that a generator can be walked only once
- watching how little work happens before you ask, and writing the expression form
Before you start
- guide 11 - a generator is something a
forloop can walk. - guide 18 - a generator is a function with one keyword changed.
-
yield instead of return
-
Running off the end
-
A generator works anywhere an iterable does
-
A generator can only be walked once
-
How little work happens before you ask
-
The generator expression
-
What the exams do with generators