Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
Generate UUID4 Values with a Python Generator
This code defines a generator function that yields mock UUID4 values, allowing you to stream unique identifiers one at a time.
import uuid
def generate_uuids(count=5):
"""Generate a stream of mock UUID4 values."""
for _ in range(count):
yield uuid.uuid4()
if __name__ == "__main__":
# Generate and print 5 UUIDs
for uid in generate_uuids(5):
print(uid)
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.