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.
Using list comprehension
list comprehension in Python is a one-liner way to perform this particular task. In this, we just shorten the task of looping in one line to generate all possible pairs of tuples with list elements.
Python3
# Python3 code to demonstrate working of # Construct Cartesian Product Tuple list # using list comprehension # 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 list comprehension res = [(a, b) for a in test_tup for b in 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)]
Using itertools.product()
This task can also be performed using the single function which 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)]
Using recursion
Here we are not using any built-in library rather we are using the concept of recursion.
Python3
def product(ar_list): if not ar_list: yield () else : for a in ar_list[ 0 ]: for prod in product(ar_list[ 1 :]): yield (a,) + prod # driver code 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)) res = list (product([test_tup,test_list])) # printing the 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)]
Please Login to comment...