cartesian product of lists in python

How to Create Cartesian Product of Two Lists in Python

Did you know that you can get a cartesian product of two lists or a list with itself in python? In this article, we will learn how to create cartesian product of two lists in Python.


How to Create Cartesian Product of Two Lists in Python

Let us say you have the following lists that you want to create cartesian product for.

lists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5, 6]
]

Starting python 2.6, you can use itertools.product to obtain cartesian product of two or more lists, or list with itself.

Here are the commands to create cartesian product of above 3 lists.

import itertools

lists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
for element in itertools.product(*lists):
    print(element)

Output will be as follows:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]

It will give you a list of tuples, where each tuple contains items from each of the 3 lists. Alternatively, you can also obtain the above output with the following commands.

for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
    print(element)

Alternatively, if you want to create cartesian product of list a=[1,2,3] with itself, you can do so in the following couple of ways.

for element in itertools.product([1, 2, 3], [1, 2, 3]):
    print(element)

Or as the following.

import itertools

lists = [
   [1, 2, 3],
   [1, 2, 3]
]
for element in itertools.product(*lists):
    print(element)

If you have two separate lists, you can also use itertools.product function to create cartesian product of both lists. Here is a simple example to create cartesian product of two lists a and b.

from itertools import product

l1 = [1,5,6]
l2 = [1,2,9]
print(list(product(l1, l2)))

Here is the output you will see.

[(1, 1), (1, 2), (1, 9), (5, 1), (5, 2), (5, 9), (6, 1), (6, 2), (6, 9)]

In this article, we have learnt how to create cartesian product of multiple lists, as well as a list with itself.

Also read:

How to Disable Triggers in PostgreSQL
Convert Text File to Excel Using Shell Script
How to Move Directory to Another Git Repository
How to Move Directory to Another Partition in Linux
How to Search PDF File in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *