CartesianProduct

CartesianProduct

CartesianProduct[ list1, list2 ] returns all pairs of an element of the first list and an element of the second list.

Usages

CartesianProduct[ list1, list2 ]

CartesianProduct[ list1, list2 ] returns a list of all pairs {a, b} with a from list1 and b from list2. The first element of list1 is combined with every element of list2 first, then the second element, and so on.

Example in out
All 3 × 2 = 6 pairs. CartesianProduct[ {1, 2, 3}, {4, 5} ] { {1, 4}, {1, 5}, {2, 4}, {2, 5}, {3, 4}, {3, 5} }
Pairs of expressions. CartesianProduct[ {a}, {x, y} ] { {a, x}, {a, y} }
Details
  • Empty list: if one of the lists is empty, CartesianProduct is left unevaluated.
Invalid input Result
CartesianProduct[ {1, 2}, 3 ] Error: the 2nd argument should be a list
CartesianProduct[ {1}, {2}, {3} ] Error: the number of arguments should be 2

See also: Map, Flatten, Concat