Open In App

Python | Extract Combination Mapping in two lists

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let’s discuss certain way in which this problem can be solved. Method : Using zip() + product() With these functions this problem can be solved and would require two steps to perform it. In the 1st step, we find all the combinations of elements using product() and as a part of 2nd step, we perform the possible pairing with the result of step 1 using zip() and output the desired result. 

Python3




# Python3 code to demonstrate working of
# Extract Combination Mapping in two lists
# using zip() + product()
from itertools import product
 
# initialize lists
test_list1 = [3, 4, 5]
test_list2 = ['x', 'y']
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Extract Combination Mapping in two lists
# using zip() + product()
res = list(list(zip(test_list1, ele)) for ele in product(test_list2, repeat = len(test_list1)))
 
# printing result
print("Mapped Combination result : " + str(res))


Output : 

The original list 1 is : [3, 4, 5] The original list 2 is : [‘x’, ‘y’] Mapped Combination result : [[(3, ‘x’), (4, ‘x’), (5, ‘x’)], [(3, ‘x’), (4, ‘x’), (5, ‘y’)], [(3, ‘x’), (4, ‘y’), (5, ‘x’)], [(3, ‘x’), (4, ‘y’), (5, ‘y’)], [(3, ‘y’), (4, ‘x’), (5, ‘x’)], [(3, ‘y’), (4, ‘x’), (5, ‘y’)], [(3, ‘y’), (4, ‘y’), (5, ‘x’)], [(3, ‘y’), (4, ‘y’), (5, ‘y’)]]

Time Complexity: O(n)
Auxiliary Space: O(n)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads