Python | Extract Combination Mapping in two lists
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 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)) |
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’)]]
Recommended Posts:
- Python | Ways to invert mapping of dictionary
- numpy.extract() in Python
- Permutation and Combination in Python
- Python | Program to count number of lists in a list of lists
- Python | Extract digits from given string
- Python | Extract numbers from string
- Python | Extract words from given string
- Python | Extract URL from HTML using lxml
- Python | Extract key-value of dictionary in variables
- Extract images from video in Python
- Python | Pandas Series.str.extract()
- Python | Extract only characters from given string
- Python | Program to extract frames using OpenCV
- Python | Extract numbers from list of strings
- Python Slicing | Extract ‘k’ bits from a given position
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.



