How To Get The Cartesian Product Of Multiple lists?

In this tutorial, we will let to know How to get the Cartesian product of multiple lists in python which we could perform using a predefined built in function product function of itertools module which could perform the cartesian product of two or more than two lists storing data of different data type.

So the same thing, we are here going to do the same using taking an example and getting the product of all three lists of python.

 Cartesian

Cartesian Products

Just like in mathematics Cartesian products are nothing but simply getting the elements in the final list equal to the number of elements by multiplying the number of elements of each list for example if we have three elements in a list1 and three elements in the list2 then the list saves the elements of the Cartesian product of both will be holding the nine elements.

And that too those nine elements would have all the possible elements combined in both the list and the same thing holds for more than two list Cartesian products.

To understand it in a better way we are going to show one example showing a Cartesian product of three lists in python and also we will see the total of all the elements that could be stored in the output.

import itertools

list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [True, False]

cartesian_ product = list( itertools. product(list1, list2, list3))

print( cartesian_ product)

Here List1, list2, and list3 all three lists are being multiplied and stored in a list called Cartesian product and it will hold the following elements

[(1, 'a', True), (1, 'a', False), (1, 'b', True), (1, 'b', False), (2, 'a', True), (2, 'a', False), (2, 'b', True), (2, 'b', False), (3, 'a', True), (3, 'a', False), (3, 'b', True), (3, 'b', False)]

And as we know we can have any number of lists for the Cartesian products as here it is for only three lists which we can simply do by adding the name of the list in the parameter of the product function.

 

To learn more about Cartesian products of two more than two lists by using built functions by importing the module for the library visit:  Cartesian product of lists in python by Stack Overflow.

 

To learn more about python and solutions for the problems faced in python along with the concepts visit Python Tutorials And Problems.

To learn more about different other programming language solutions and concepts visit: beta python programming languages Solutions.  And Learn more to grow your knowledge.

Leave a Comment

%d bloggers like this: