Python Comprehensions
Build lists and dicts in one line, and stream values with generators.
Why it matters: Comprehensions filter scores and clean text. Generators stream large datasets without loading everything into memory.
Basics
List Comprehension
A list comprehension builds a list from a loop:
[expr for item in seq]
Add a filter with if:
[x for x in scores if x > 0.7]
Keep it to one loop and one condition. Longer logic belongs in a normal for-loop.
Tiny example
Keep only high scores in one line.
scores = [0.9, 0.4, 0.8]
kept = [s for s in scores if s >= 0.7]
print(kept)Basics
Dict and Set Comprehension
Dict comprehension uses braces and a key:value pair:
{k: v for k, v in pairs}
Set comprehension uses braces with one expression:
{x.lower() for x in words}
Same idea as lists: short transform, easy to read.
Tiny example
Build a small dict from names and lengths.
words = ["rag", "ml"]
lengths = {w: len(w) for w in words}
print(lengths)Basics
Generators
A generator function uses yield instead of return. Each yield pauses and sends one value.
Generator expressions use parentheses: (x * 2 for x in nums).
Values are made on demand, so memory stays low. Generators are single-use. Call the function again to restart.
Tiny example
Yield one batch name at a time.
def batches(n):
for i in range(n):
yield f"batch-{i}"
print(list(batches(3)))Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: clean and filter chunks
Strip, lowercase, and keep only long enough text.
In AI / ML: RAG prep often cleans and filters documents in one line.
example.py
Python
docs = [" Python ", "AI", " Machine Learning "]
cleaned = [d.strip().lower() for d in docs if len(d.strip()) > 2]
print(cleaned)AI / ML example 2
AI / ML: yield training batches
Memory stays flat while you walk the data.
In AI / ML: Training loops stream rows in batches instead of one giant list.
example.py
Python
def batched(items, size):
batch = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
for batch in batched(range(7), 3):
print(batch)Takeaways
- 1Comprehensions build lists, dicts, or sets in one readable line.
- 2Keep them short: one loop and one filter.
- 3Generators yield values lazily and are single-use.