Core Python › 5 of 14
Comprehensions & Generators
Concise transforms and memory-efficient streaming.
python
squares = [x**2 for x in range(5) if x % 2 == 0]
vocab = {w: i for i, w in enumerate(words)}
def batches(data, size):
for i in range(0, len(data), size):
yield data[i:i + size]
total = sum(len(b) for b in batches(dataset, 32))Generators produce items lazily — ideal for datasets too large for memory.
⚡ Quick check
- ✓ [f(x) for x in xs if c]
- ✓ yield makes a generator
- ✓ (expr for x in xs) is lazy