Python program to find Cartesian product of two lists


Suppose we have two list of data l1 and l2. We have to find Cartesian product of these two lists. As we know if two lists are like (a, b) and (c, d) then the Cartesian product will be {(a, c), (a, d), (b, c), (b, d)}. To do this we shall use itertools library and use the product() function present in this library. The returned value of this function is an iterator. We have to convert it into list by passing the output into list() constructor.

So, if the input is like l1 = [1,5,6] l2 = [1,2,9], then the output will be [(1, 1), (1, 2), (1, 9), (5, 1), (5, 2), (5, 9), (6, 1), (6, 2), (6, 9)]

To solve this, we will follow these steps −

  • x := product(l1, l2) to get iterator of Cartesian products

  • ret := list(x) to convert x iterator to list

  • return ret

Example

Let us see the following implementation to get better understanding

from itertools import product
def solve(l1, l2):
   return list(product(l1, l2))

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

Input

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

Output

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

Updated on: 11-Oct-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements