How to use list comprehension In Python

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

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. 

Similar Reads

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

Using itertools.product()

...

Using recursion

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():...

Using map() and lambda function

...

Contact Us