Function Repository Resource:

CartesianProduct

Source Notebook

Compute the Cartesian product of two lists

Contributed by: Jordan Hasler, Wolfram|Alpha Math Team

ResourceFunction["CartesianProduct"][list1,list2]

compute the Cartesian product of list1 and list2.

Examples

Basic Examples (2) 

Find the Cartesian product of two lists of integers:

In[1]:=
ResourceFunction["CartesianProduct"][{1, 2}, {3, 4, 5}]
Out[1]=

The lists given to CartesianProduct can contain any type of expression:

In[2]:=
ResourceFunction["CartesianProduct"][{3/2, Sqrt[Pi]}, {a, b, c}]
Out[2]=

Scope (2) 

Compute the Cartesian product:

In[3]:=
ResourceFunction["CartesianProduct"][{1, 2, 3}, {5, 6, 7}]
Out[3]=

Visualize the Cartesian product:

In[4]:=
ListPlot[ResourceFunction["CartesianProduct"][{1, 2, 3}, {5, 6, 7}]]
Out[4]=

Properties and Relations (4) 

Find and compare the Cartesian product to equivalent Wolfram Language expressions:

In[5]:=
ResourceFunction["CartesianProduct"][{1, 6, 7}, {3, 4, 5}]
Out[5]=

The Cartesian product is equivalent to Distribute:

In[6]:=
Distribute[{{1, 6, 7}, {3, 4, 5}}, List]
Out[6]=

The Cartesian product can be written in terms of Outer:

In[7]:=
Join @@ Outer[List, {1, 6, 7}, {3, 4, 5}]
Out[7]=

The Cartesian product can be written in terms of Tuples:

In[8]:=
Tuples[{{1, 6, 7}, {3, 4, 5}}]
Out[8]=

Publisher

Wolfram|Alpha Math Team

Version History

  • 2.0.0 – 23 March 2023
  • 1.0.0 – 09 December 2022

Related Resources

Author Notes

To view the full source code for CartesianProduct, evaluate the following:

In[1]:=
SystemOpen[
 FileNameJoin[{DirectoryName[FindFile["ResourceFunctionHelpers`"]], "CartesianProduct.wl"}]]

License Information