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 web development domain. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension
This is one-liner way to perform this particular task. In this, we just shorten the task of loop in one line to generate all possible pairs of tuple with list elements.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

 

Method #2 : Using itertools.product()
This task can also be performed using the single function which internally performs the task of returning the required Cartesian Product.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Construct Cartesian Product Tuple list
# 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))

chevron_right


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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.