Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
How to Generate Permutations of Length r in Python
Generate all ordered arrangements of length r from a given list of elements using itertools.permutations.
from itertools import permutations
def generate_permutations(elements, r):
"""Generate all r-length permutations of the given elements."""
return list(permutations(elements, r))
if __name__ == "__main__":
elements = ['A', 'B', 'C']
r = 2
result = generate_permutations(elements, r)
print(f"Ele…
Merge Data with Comprehension and Generator in Python
Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.
def merge_data(users, orders):
"""
Merge user and order data using a dictionary comprehension
and a generator expression for filtering.
"""
# Build a lookup: user_id -> user name
user_map = {user["id"]: user["name"] for user in users}
# Generator: yield orders with user names attached
…
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.