# Cartesian product of more than two sets

Here you see how to produce a cartesian product of two sets. How can we obtain the cartesian product of three or more sets? CartesianProduct[l1,l2,l3] doesn't work.

• Flatten /@ CartesianProduct[CartesianProduct[list1, list2], list 3]? Commented Sep 29, 2017 at 19:02
• Have you seen Tuples[]? Commented Sep 29, 2017 at 19:02
• @J.M. Of course! Tuples[{S, S, S}] did the trick. Thanks :-) Commented Sep 29, 2017 at 19:12

As @JM said, use Tuples[{set1, set2, set3, ...}].

CartiesianProduct is part of the obsolete and underdocumented Combinatorica package. Try to avoid this package unless you cannot find some functionality elsewhere.

If set1, set2 are lists the example look like the following:

In: Tuples[{{a, b}, {c, d}}]

Out: {{a, c}, {a, d}, {b, c}, {b, d}}


You can also use Distribute:

cpF = Distribute[{##}, List] &;

cpF[{a, b}, {u, v}, {r, s, t}]


{{a, u, r}, {a, u, s}, {a, u, t},
{a, v, r}, {a, v, s}, {a, v, t},
{b, u, r}, {b, u, s}, {b, u, t},
{b, v, r}, {b, v, s}, {b, v, t}}