Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Use product to generate coordinate pairs

Create Cartesian products between two iterables to generate coordinate pairs. itertools.product simplifies the task.

Python practice14 minModules & Standard LibraryIntermediateLast updated March 23, 2026

Problem statement

Given two iterables (e.g., lists, tuples, ranges, strings), return their Cartesian product as a list of 2-tuples. Each tuple should contain one element from the first iterable followed by one from the second. Preserve the ordering produced by itertools.product. If either iterable is empty, return an empty list.

Task

Implement a function that returns the Cartesian product of two iterables as a list of tuples, preserving order.

Examples

Two simple lists

Input

product_pairs([1, 2], ['a', 'b'])

Output

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

All combinations of elements from the first and second lists.

Input format

A call: product_pairs(xs, ys) where xs and ys are iterables.

Output format

A list of 2-tuples (x, y) for each x in xs and y in ys.

Constraints

Do not convert iterables unnecessarily; returning list(product(...)) is acceptable. Preserves the order where outer loop is xs and inner loop is ys.

Samples

Sample 1

Input

product_pairs([0, 1], 'ab')

Output

[(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]

Combines numbers with characters producing coordinate-like pairs.