- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

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

- Related Questions & Answers
- Cartesian product of two sets in JavaScript
- Python program to find Intersection of two lists?
- Python program to find Union of two or more Lists?
- C# program to find Intersection of two lists
- Program to find union of two given linked lists in Python
- Python Program to Find the Product of two Numbers Using Recursion
- Cartesian product of multiple arrays in JavaScript
- 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 minimum difference between two elements from two lists in Python
- Python program to find missing and additional values in two lists?
- Program to find out the dot product of two sparse vectors in Python
- C# program to find additional values in two lists
- Program to find cost to reach final index of any of given two lists in Python

Advertisements