The goal is to combine each item from first list with each item from second list in every possible unique way. If we want to get all possible combinations from two lists. Python’s itertools library has a function called a product that makes it easy to generate combinations of items from multiple lists.
import itertools
a = ["a", "b"]
b = [1, 2]
#It generate all possible combinations of elements from both lists
# Convert the result into a list of tuples
combinations = list(itertools.product(a, b))
print(combinations)
Output
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
itertools.productautomatically creates the combinations of elements from both lists. We uselist()to convert the result into a list of tuples.
There are other methods which can be used that are both fast and efficient :
Using itertools.permutations
itertools.permutations function creates all possible permutations of a given list. We can combine this with zip to create unique combinations of two lists.
import itertools
a = ["a", "b"]
b = [1, 2]
# Generate all 2-length permuations of pairs by zipping lists
combinations = list(itertools.permutations(zip(a, b), 2))
print(combinations)
Output
[(('a', 1), ('b', 2)), (('b', 2), ('a', 1))]
- The zip(a, b) combines the two lists element-wise into pairs, and itertools.permutations then creates all possible orders of these pairs.
- This method returns all unique permutations, including reversed combinations.
Using a Nested Loop
We can get all combinations is by using two loops. We can loop through each element in both lists and combine them.
X = ["a", "b"]
Y = [1, 2]
# Initialize an empty list
combinations = []
# Loop through each element in List_1
for x in X:
# Loop through each element in List_2
for y in Y:
combinations.append((x, y))
print(combinations)
Output
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
Using List Comprehension
If we have to write cleaner and shorter code, we can use list comprehension to achieve the same result. This is essentially the same thing as using loops but in a single line. It’s a concise way to combine elements.
X = ["a", "b"]
Y = [1, 2]
#list combination of all possible elemenst of two lists(X and Y)
combinations = [(x, y) for x in X for y in Y]
print(combinations)
Output
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]