Batu Lab NotesPractical developer guides

Enumerate a small option grid with product

By Batu ยท English technical notes

Also published in our Blogger archive.

A Cartesian product combines one value from each input collection. Here, product(regions, formats) constructs every region-and-format option for a small export screen. The order is useful: the leftmost input changes more slowly, so each region is paired with every format before the next region begins. With two regions and three formats, the grid contains six tuples.

The code converts the iterator to a list because it needs to validate and print every entry in this intentionally small grid. Its assertions verify the six expected synthetic combinations and the first and last tuple. They do not validate whether a real export service supports those combinations. For dynamic or large collections, avoid materializing the whole product unless its size is known to be manageable; the count is the product of the input lengths, and it grows quickly as dimensions are added.

itertools.product is a standard-library function and no newer API is used here. repeat can repeat the same iterable across several positions, but this example deliberately supplies separate collections because region and format have different meanings. The documentation also notes that the implementation consumes the input iterables into internal pools before yielding results. That makes it a poor fit for unbounded input iterators.

AI-assistance disclosure: this article was drafted with AI assistance; confirm domain constraints before using generated configurations in production.

Source: Python itertools.product documentation.

from itertools import product

regions = ("eu", "us")
formats = ("csv", "json", "parquet")
options = list(product(regions, formats))

assert len(options) == 6
assert options[0] == ("eu", "csv")
assert options[-1] == ("us", "parquet")
assert set(options) == {
    ("eu", "csv"), ("eu", "json"), ("eu", "parquet"),
    ("us", "csv"), ("us", "json"), ("us", "parquet"),
}

for region, file_format in options:
    print(f"{region}:{file_format}")
eu:csv
eu:json
eu:parquet
us:csv
us:json
us:parquet