Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
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.
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")
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.
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"]…
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.
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…
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.
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…
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.
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…
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.