Write a Python program to get all unique combinations of two Lists


This program uses the itertools library in Python to generate all possible permutations of two lists, l1 and l2. The permutations function is used to generate all possible permutations of the elements in the first list (l1) with a length equal to the length of the second list (l2).

The program then uses a for loop to iterate over each combination in the permutations, and uses the zip function to combine each element in the combination with the corresponding element in the second list. The result of each combination is then appended to the unique list.

Finally, the program prints the unique list, which contains all possible permutations of the elements of the two lists, with elements of both lists combined into tuples.

Source Code

import itertools
from itertools import permutations
l1 = ['A','B','C']
l2 = [1,2,3]
unique = []
permut = itertools.permutations(l1, len(l2))
for comb in permut:
	zipped = zip(comb, l2)
	unique.append(list(zipped))
 
print(unique)

Output

[[('A', 1), ('B', 2), ('C', 3)], [('A', 1), ('C', 2), ('B', 3)], [('B', 1), ('A', 2), ('C', 3)], [('B', 1), ('C', 2), ('A', 3)], [('C', 1), ('A', 2), ('B', 3)], [('C', 1), ('B', 2), ('A', 3)]]


Example Programs