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]? – march Sep 29 '17 at 19:02
• Have you seen Tuples[]? – J. M.'s technical difficulties Sep 29 '17 at 19:02
• @J.M. Of course! Tuples[{S, S, S}] did the trick. Thanks :-) – Filburt Sep 29 '17 at 19:12

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

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

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}}