Reference library

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

10 matches
Comprehensions & generators easy

Build a lazy generator to read file lines in Python

Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.

generator file-io lazy
Python
def lazy_lines(filepath):
    """Yield lines from a file one at a time without loading the whole file into memory."""
    with open(filepath, 'r', encoding='utf-8') as file:
        for line in file:
            yield line.rstrip('\n')


if __name__ == "__main__":
    # Create a sample file to demonstrate
    sample_c…
14 0 Open
Comprehensions & generators easy

Generator Function to Yield an Infinite Counter in Python

This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.

generators infinite sequences yield
Python
def infinite_counter(start=0):
    count = start
    while True:
        yield count
        count += 1

if __name__ == "__main__":
    counter = infinite_counter(5)
    for _ in range(5):
        print(next(counter))
14 0 Open
Comprehensions & generators medium

How to Build a Backpressure Generator Pause Producer Demo in Python

Demonstrates a producer–consumer pattern with a fixed-size buffer that pauses production when full, simulating backpressure.

backpressure producer-consumer deque
Python
import time
import collections

def producer(buffer, max_size, items):
    """Adds items to the buffer until full, then pauses."""
    for item in items:
        while len(buffer) >= max_size:
            print(f"Buffer full ({len(buffer)}/{max_size}) — producer paused")
            time.sleep(0.1)
        buffer.appe…
14 0 Open
Comprehensions & generators easy

How to Close a Generator and Handle GeneratorExit in Python

This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.

generators generator-exit close
Python
def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    finally:
        print(f"Generator closed after countdown completed")


if __name__ == "__main__":
    gen = countdown(5)
    print(next(gen))
    print(next(gen))
    gen.close()
    print("Generator closed explicitly")
12 0 Open
Comprehensions & generators easy

How to Parse Data with Generators and Comprehensions in Python

This code demonstrates using a generator expression to filter active users and a dictionary comprehension to aggregate scores by name.

generator expressions dictionary comprehensions filtering
Python
def parse_data_helper(raw_records):
    """Extract active users' names and scores from raw records."""
    parsed = (
        (record["name"], record["score"])
        for record in raw_records
        if record["active"] and record["score"] >= 0
    )
    return list(parsed)


def aggregate_scores(parsed_data):
    "…
15 0 Open
Comprehensions & generators medium

How to Throw an Exception into a Python Generator

This code demonstrates how to use the .throw() method on a generator to inject an exception at its current yield point and let it recover gracefully.

generator throw exception
Python
def demo_throw_into_generator():
    """Demonstrate throwing an exception into a running generator."""
    def counter():
        """Generator that counts until interrupted."""
        try:
            i = 0
            while True:
                yield i
                i += 1
        except ValueError as e:
        …
12 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators in Python

Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.

comprehensions generators yield
Python
def demonstrate_comprehensions_generators():
    # List comprehension: transform and filter in one line
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    squares = [num ** 2 for num in numbers if num % 2 == 0]
    print(f"Square of even numbers (list comprehension): {squares}")

    # Set comprehension: unique values
…
15 0 Open
Comprehensions & generators medium

How to stream parse JSON arrays in Python

This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.

json generator streaming
Python
import json


def json_array_stream(items):
    """Generator that yields JSON-encoded values one at a time."""
    yield "["
    for i, item in enumerate(items):
        if i > 0:
            yield ","
        yield json.dumps(item)
    yield "]"


def parse_json_stream(stream):
    """Consumes a stream of JSON fragme…
14 0 Open
Comprehensions & generators easy

Sum of Squares with a Generator Expression in Python

This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.

generator sum squares
Python
def sum_of_squares(n):
    return sum(x * x for x in range(1, n + 1))

if __name__ == "__main__":
    print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
    print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
14 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 0 Open

Browse by section

Each section groups closely related Python snippets.

Comprehensions & generators — Python code examples

What you will find here

This page collects comprehensions & generators snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.