- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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)]

- Related Articles
- Python program to find Intersection of two lists?
- Python program to find Union of two or more Lists?
- Cartesian product of two sets in JavaScript
- Program to find union of two given linked lists in Python
- C# program to find Intersection of two lists
- Python program to find missing and additional values in two lists?
- Python Program to Find the Product of two Numbers Using Recursion
- Program to find minimum difference between two elements from two lists in Python
- Program to find the largest product of two distinct elements in Python
- C# program to find Union of two or more Lists
- Program to find median of two sorted lists in C++
- Program to find cost to reach final index of any of given two lists in Python
- Program to find out the dot product of two sparse vectors in Python
- Python program to list the difference between two lists.
- Python Program to Merge Two Lists and Sort it