Reference library

Comprehensions & generators

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

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

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.