How to use itertools.product() In Python
This task can also be performed using a single function that internally performs the task of returning the required Cartesian Product, here we are using itertools.product():
Python3
# using itertools.product() from itertools import product # initialize list and tuple test_list = [ 1 , 4 , 6 , 7 ] test_tup = ( 1 , 3 ) # printing original list and tuple print ( "The original list : " + str (test_list)) print ( "The original tuple : " + str (test_tup)) # Construct Cartesian Product Tuple list # using itertools.product() res = list (product(test_tup, test_list)) # printing result print ( "The Cartesian Product is : " + str (res)) |
Output
The original list : [1, 4, 6, 7] The original tuple : (1, 3) The Cartesian Product is : [(1, 1), (1, 4), (1, 6), (1, 7), (3, 1), (3, 4), (3, 6), (3, 7)]
Python | Construct Cartesian Product Tuple list
Sometimes, while working with data, we need to create data as all possible pairs of containers. This type of application comes from the web development domain. Let’s discuss certain ways in which this task can be performed.