Reference library

Comprehensions & generators

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

8 matches
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 Generate Cartesian Product Combinations in Python

Use itertools.product to generate every combination across multiple iterables, a pattern common for product variant generation.

itertools cartesian product combinations
Python
from itertools import product

def generate_cartesian_combinations(*iterables):
    """Generate all Cartesian product combinations of given iterables."""
    return list(product(*iterables))

if __name__ == "__main__":
    colors = ["red", "green", "blue"]
    sizes = ["S", "M", "L"]
    styles = ["t-shirt", "hoodie"]…
13 0 Open
Comprehensions & generators medium

How to Generate Primes with a Generator in Python

Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.

generators sieve primes
Python
def prime_generator(limit):
    sieve = [True] * (limit + 1)
    sieve[0] = sieve[1] = False

    for i in range(2, int(limit ** 0.5) + 1):
        if sieve[i]:
            for j in range(i * i, limit + 1, i):
                sieve[j] = False

    return (num for num, is_prime in enumerate(sieve) if is_prime)


if __n…
15 0 Open
Comprehensions & generators easy

How to Generate a Collatz Sequence in Python

Generate the Collatz sequence for a given positive integer by repeatedly applying the 3n+1 rule until reaching 1.

collatz sequence loops
Python
def collatz_sequence(n):
    if n <= 0:
        raise ValueError("n must be a positive integer")
    sequence = [n]
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        sequence.append(n)
    return sequence

if __name__ == "__main__":
    start = 7
    result…
14 0 Open
Comprehensions & generators easy

How to Repeat a Generator Cycle Single Value in Python

Build a generator that repeats a single value across multiple cycles, each cycle adding an extra repetition to mark its completion.

generators loops repeat
Python
def repeat_with_cycle(value, cycle_limit, repetitions):
    """
    Repeats a single value until reaching a cycle limit,
    then yields the value one more time to demonstrate a full cycle.
    
    Args:
        value: The single value to repeat.
        cycle_limit: Number of repetitions per cycle.
        repetitio…
13 0 Open
Comprehensions & generators easy

How to Reset Python's Random Seed for Deterministic Output

This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.

random seeding deterministic
Python
import random

def seeded_random_sequence(seed, count=5, low=1, high=100):
    random.seed(seed)
    return [random.randint(low, high) for _ in range(count)]

if __name__ == "__main__":
    seed_value = 42
    first_run = seeded_random_sequence(seed_value)
    print("First run:", first_run)

    # Reset seed and gener…
12 0 Open
Comprehensions & generators medium

How to filter a generator with a predicate function in Python

This code defines a generator function that yields only items from an iterable that satisfy a given predicate, then tests it with even and positive number filters.

generators filtering lazy evaluation
Python
def filter_gen(predicate, iterable):
    for item in iterable:
        if predicate(item):
            yield item

def is_even(num):
    return num % 2 == 0

def is_positive(num):
    return num > 0

if __name__ == "__main__":
    numbers = range(-5, 10)
    
    even_numbers = list(filter_gen(is_even, numbers))
    p…
10 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

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.