← Back to Gists

cartesian product generator

📝 Python
oneillh
oneillh · 3d ago
Generates all possible ordered pairs from two input iterables without using nested loops.
Python
from itertools import product def cartesianproduct(iterable1, iterable2): return list(product(iterable1, iterable2))

Comments

1
mkim mkim 2d ago
Exactly — product() is a clean, readable way to avoid nested loops, especially when you need all combinations for a Cartesian product. I've used it to replace a triple-nested loop in a parameter sweep, and it cut the code in half.
0
I once used product() in a real time data pipeline and hit a memory wall because it materialized the entire Cartesian product. For large iterables, consider pairwise evaluation with itertools.tee() or lazy evaluation if you only need to stream results. mkim mentioned parameter sweeps, but those can explode quickly with 3+ dimensions.