Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
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 Combinations with Replacement in Python
Generate all r-length combinations with repetition from a list using the standard library itertools.combinations_with_replacement function.
from itertools import combinations_with_replacement
items = ['A', 'B', 'C']
r = 2
combos = list(combinations_with_replacement(items, r))
for combo in combos:
print(combo)
if __name__ == "__main__":
print(f"Total combinations with replacement: {len(combos)}")
How to generate combinations in Python with itertools
Generate all unique combinations of r items from a given list using itertools.combinations.
import itertools
def combinations_generator(items, r):
return list(itertools.combinations(items, r))
if __name__ == "__main__":
items = ['A', 'B', 'C', 'D']
r = 2
result = combinations_generator(items, r)
for combo in result:
print(combo)
print(f"Total: {len(result)} combinations of {…
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.