Table of Contents
- List comprehensions
- Generator expressions (“tuple comprehension”)
- Functions with `yield`
- Lambda functions
- Declaring global variables
- Putting it all together
- Exercise 1 — Sensor pipeline
List comprehensions
A list comprehension builds the entire list immediately, in one expression:
temps = [21.4, 24.9, 19.8, 30.2, 26.5]
celsius_above_25 = [t for t in temps if t > 25]
print(celsius_above_25)Output:
[30.2, 26.5]
With a transformation applied:
fahrenheit = [t * 1.8 + 32 for t in temps]
print(fahrenheit)Output:
[70.52, 76.82, 67.64, 86.36, 79.7]
Observation
The whole list is allocated up front. Fine for 5 items, less fine for 50 million readings.
Generator expressions (“tuple comprehension”)
Replace the square brackets with parentheses and you get a generator expression — Python has no real “tuple comprehension”, this is the equivalent construct:
gen = (t * 1.8 + 32 for t in temps)
print(gen)Output:
<generator object <genexpr> at 0x7f8b1c2e3d40>
Nothing has run yet. Values are produced one at a time as you consume them:
print(next(gen))
print(next(gen))
print(list(gen)) # remaining itemsOutput:
70.52
76.82
[67.64, 86.36, 79.7]
Exhaustion
A generator can be consumed once. After the last item,
next()raisesStopIterationandlist(gen)returns[]. Create a fresh generator expression if you need to iterate again.
Memory comparison
import sys
big_list = [x**2 for x in range(1_000_000)]
big_gen = (x**2 for x in range(1_000_000))
print(f'list : {sys.getsizeof(big_list):>10,d} bytes')
print(f'gen : {sys.getsizeof(big_gen):>10,d} bytes')Output:
list : 8,448,728 bytes
gen : 200 bytes
Takeaway
The generator holds only the loop state (~200 bytes); the list holds all million results. Use a generator expression whenever the data is consumed sequentially.
Functions with yield
Any function containing yield becomes a generator function. Calling it does not run the body — it returns a generator object. Each next() resumes execution until the next yield.
A login-attempt generator
def login_attempts(users):
"""Yield a verdict for each username, one at a time."""
failures = 0
for user in users:
if user != 'fulano':
failures += 1
yield f'{user}: DENIED (failure #{failures})'
else:
yield f'{user}: OK'
for verdict in login_attempts(['sicrano', 'fulano', 'beltrano']):
print(verdict)Output:
sicrano: DENIED (failure #1)
fulano: OK
beltrano: DENIED (failure #2)
Note how failures is local state kept alive between yields — no global, no class needed. This is exactly the state-management problem from PY51-python-classes-intro, solved with the generator’s own suspended frame.
Inspecting the generator
gen = login_attempts(['sicrano', 'fulano'])
print(gen)
print(next(gen))
print(next(gen))Output:
<generator object login_attempts at 0x7f8b1c2e3f80>
sicrano: DENIED (failure #1)
fulano: OK
Lambda functions
A lambda is a small anonymous function — useful as a key, a quick transformation inside a comprehension, or a factory:
to_f = lambda t: t * 1.8 + 32
temps = [21.4, 24.9, 19.8]
print([to_f(t) for t in temps])Output:
[70.52, 76.82, 67.64]
As a sort key, sorting the login log by number of failures:
attempts = [('sicrano', 1), ('beltrano', 2), ('fulano', 0)]
print(sorted(attempts, key=lambda pair: pair[1]))Output:
[('fulano', 0), ('sicrano', 1), ('beltrano', 2)]
Style note
PEP 8 recommends assigning a lambda to a name only when you would have written a one-line
defanyway. For anything longer, usedef.
Declaring global variables
Generators can read globals freely; writing to one requires the global keyword, exactly as shown in Version 2 of the classes note:
MAX_FAILURES = 3 # global constant — readable everywhere
def remaining_budget():
"""Reads the global without needing `global` (read-only)."""
return MAX_FAILURES - failures_so_far
failures_so_far = 0
def register_failure():
global failures_so_far # required to REBIND a global
failures_so_far += 1
register_failure()
register_failure()
print(remaining_budget())Output:
1
Anti-pattern
Same warning as in PY51-python-classes-intro:
globalmutable state is fragile. Prefer generator-local state (likefailuresin theyieldexample above) or class attributes.
Putting it all together
A small pipeline combining every topic: a yield-based sensor feed, a lambda conversion, and a generator expression that filters — all lazy end-to-end:
def sensor_stream(readings):
"""Generator: simulates a live feed, one reading at a time."""
for r in readings:
yield r
raw = sensor_stream([21.4, 24.9, 19.8, 30.2, 26.5])
to_f = lambda t: t * 1.8 + 32 # lambda
hot = (r for r in raw if r > MAX_HOT) # generator expression
MAX_HOT = 25.0 # module-level constant
for reading in hot: # consumed lazily
print(f'{reading}°C = {to_f(reading):.2f}°F')Output:
30.2°C = 86.36°F
26.5°C = 79.70°F
No intermediate list ever exists: raw yields → the hot generator filters → the loop converts and prints, one item at a time.
Exercise 1 — Sensor pipeline
Build a generator function celsius_to_fahrenheit(readings) that:
- Uses
yieldto emit each converted value one at a time. - Skips any value that is not a
float(mimic theTypeErrorvalidation from PY51-python-classes-intro). - Is consumed by a generator expression that keeps only values above
80.0°F. - Uses a
lambdaas the conversion helper.
Try it
What happens if you pass the same generator object to two
forloops? How would you “reset” the pipeline?
Related notes
- PY51-python-classes-intro — state, classes and properties