Comprehensions & Generators

[expr for x in it if cond] — the pattern you will use daily. Nested: [[cell for cell in row] for row in matrix]. Dict: {k: v for k, v in pairs.items()}. Generators (x for x in data) are lazy — they do not compute until iterated, saving memory on large datasets.

💻 Code example

# Clean and tokenize text in one line
clean = [t.lower().strip() for t in raw if len(t) > 2]

# Generator for memory-efficient large dataset processing
def batch_generator(data, batch_size=32):
    for i in range(0, len(data), batch_size):
        yield data[i:i + batch_size]

💬 Deep Dive with AI