Reference library

Comprehensions & generators

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

1 match
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

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.