Open In App

Python program to get all unique combinations of two Lists

Last Updated : 14 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The combination is a mathematical technique that calculates the number of possible arrangements in a collection of items or list. In combination order of selection doesn’t matter. The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. 

Example:

List_1 = ["a","b"]
List_2 = [1,2]
Unique_combination = [[('a',1),('b',2)],[('a',2),('b',1)]] 

Method 1: Using permutation() of itertools package and zip() function.

Approach :

  • Import itertools package and initialize list_1 and list_2.
  • Create an empty list of ‘unique_combinations’ to store the resulting combinations so obtained.
  • Call itertools.permutations( ) which will return permutations of list_1 with length of list_2. Generally, the length of the shorter list is taken and if both lists are equal, use either.
  • For loop is used and zip() function is called to pair each permutation and shorter list element into the combination.
  • Then each combination is converted into a list and append to the combination list.

Below is the implementation.

Python3




# python program to demonstrate
# unique combination of two lists
# using zip() and permutation of itertools
 
# import itertools package
import itertools
from itertools import permutations
 
# initialize lists
list_1 = ["a", "b", "c","d"]
list_2 = [1,4,9]
 
# create empty list to store the
# combinations
unique_combinations = []
 
# Getting all permutations of list_1
# with length of list_2
permut = itertools.permutations(list_1, len(list_2))
 
# zip() is called to pair each permutation
# and shorter list element into combination
for comb in permut:
    zipped = zip(comb, list_2)
    unique_combinations.append(list(zipped))
 
# printing unique_combination list
print(unique_combinations)


Output :

[[(‘a’, 1), (‘b’, 4), (‘c’, 9)], [(‘a’, 1), (‘b’, 4), (‘d’, 9)], [(‘a’, 1), (‘c’, 4), (‘b’, 9)], [(‘a’, 1), (‘c’, 4), (‘d’, 9)], [(‘a’, 1), (‘d’, 4), (‘b’, 9)], [(‘a’, 1), (‘d’, 4), (‘c’, 9)], [(‘b’, 1), (‘a’, 4), (‘c’, 9)], [(‘b’, 1), (‘a’, 4), (‘d’, 9)], [(‘b’, 1), (‘c’, 4), (‘a’, 9)], [(‘b’, 1), (‘c’, 4), (‘d’, 9)], [(‘b’, 1), (‘d’, 4), (‘a’, 9)], [(‘b’, 1), (‘d’, 4), (‘c’, 9)], [(‘c’, 1), (‘a’, 4), (‘b’, 9)], [(‘c’, 1), (‘a’, 4), (‘d’, 9)], [(‘c’, 1), (‘b’, 4), (‘a’, 9)], [(‘c’, 1), (‘b’, 4), (‘d’, 9)], [(‘c’, 1), (‘d’, 4), (‘a’, 9)], [(‘c’, 1), (‘d’, 4), (‘b’, 9)], [(‘d’, 1), (‘a’, 4), (‘b’, 9)], [(‘d’, 1), (‘a’, 4), (‘c’, 9)], [(‘d’, 1), (‘b’, 4), (‘a’, 9)], [(‘d’, 1), (‘b’, 4), (‘c’, 9)], [(‘d’, 1), (‘c’, 4), (‘a’, 9)], [(‘d’, 1), (‘c’, 4), (‘b’, 9)]] 

Time complexity: O(n! * m), where n is the length of list_1 and m is the length of list_2.
Auxiliary Space: O(n! * m), as we are storing all the unique combinations in the “unique_combinations” list.

Method 2 : Using product() of itertools package and zip() function.

Approach :

  • Import itertools package and initialize list_1 and list_2.
  • Create an empty list of ‘unique_combinations’ to store the resulting combinations so obtained.
  • product() is called to find all possible combinations of elements.
  • And zip() is used to pair up all these combinations, converting each element into a list and append them to the desired combination list.

Below is the implementation.

Python3




# python program to demonstrate
# unique combination of two lists
# using zip() and product() of itertools
 
# import itertools package
import itertools
from itertools import product
 
# initialize lists
list_1 = ["b","c","d"]
list_2 = [1,4,9]
 
# create empty list to store the combinations
unique_combinations = []
 
# Extract Combination Mapping in two lists
# using zip() + product()
unique_combinations = list(list(zip(list_1, element))
                           for element in product(list_2, repeat = len(list_1)))
 
# printing unique_combination list
print(unique_combinations)


Output :

[[(‘b’, 1), (‘c’, 1), (‘d’, 1)], [(‘b’, 1), (‘c’, 1), (‘d’, 4)], [(‘b’, 1), (‘c’, 1), (‘d’, 9)], [(‘b’, 1), (‘c’, 4), (‘d’, 1)], [(‘b’, 1), (‘c’, 4), (‘d’, 4)], [(‘b’, 1), (‘c’, 4), (‘d’, 9)], [(‘b’, 1), (‘c’, 9), (‘d’, 1)], [(‘b’, 1), (‘c’, 9), (‘d’, 4)], [(‘b’, 1), (‘c’, 9), (‘d’, 9)], [(‘b’, 4), (‘c’, 1), (‘d’, 1)], [(‘b’, 4), (‘c’, 1), (‘d’, 4)], [(‘b’, 4), (‘c’, 1), (‘d’, 9)], [(‘b’, 4), (‘c’, 4), (‘d’, 1)], [(‘b’, 4), (‘c’, 4), (‘d’, 4)], [(‘b’, 4), (‘c’, 4), (‘d’, 9)], [(‘b’, 4), (‘c’, 9), (‘d’, 1)], [(‘b’, 4), (‘c’, 9), (‘d’, 4)], [(‘b’, 4), (‘c’, 9), (‘d’, 9)], [(‘b’, 9), (‘c’, 1), (‘d’, 1)], [(‘b’, 9), (‘c’, 1), (‘d’, 4)], [(‘b’, 9), (‘c’, 1), (‘d’, 9)], [(‘b’, 9), (‘c’, 4), (‘d’, 1)], [(‘b’, 9), (‘c’, 4), (‘d’, 4)], [(‘b’, 9), (‘c’, 4), (‘d’, 9)], [(‘b’, 9), (‘c’, 9), (‘d’, 1)], [(‘b’, 9), (‘c’, 9), (‘d’, 4)], [(‘b’, 9), (‘c’, 9), (‘d’, 9)]] 
 

Time complexity: O(n! * m), where n is the length of list_1 and m is the length of list_2.
Auxiliary Space: O(n! * m), as we are storing all the unique combinations in the “unique_combinations” list.

Method 3:use nested loops:

In this program generates all possible unique combinations of elements from two input lists. It uses nested loops to iterate over each element in both lists and adds them as a tuple to the unique_combinations list. The final output is a list of all possible combinations of elements from the two input list

Python3




list_1 = ["b", "c", "d"]
list_2 = [1, 4, 9]
 
unique_combinations = []
 
for i in range(len(list_1)):
    for j in range(len(list_2)):
        unique_combinations.append((list_1[i], list_2[j]))
 
print(unique_combinations)


Output

[('b', 1), ('b', 4), ('b', 9), ('c', 1), ('c', 4), ('c', 9), ('d', 1), ('d', 4), ('d', 9)]

The time complexity of this method is O(n^2), where n is the length of the lists.

The space complexity is also O(n^2) because it creates a list of tuples that has the same number of elements as the product of the lengths of the input lists.



Similar Reads

itertools.combinations() module in Python to print all possible combinations
Given an array of size n, generate and print all possible combinations of r elements in array. Examples: Input : arr[] = [1, 2, 3, 4], r = 2 Output : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]Recommended: Please try your approach on {IDE} first, before moving on to the solution. This problem has existing recursive solution please refer Print
2 min read
Python - All Possible unique K size combinations till N
Sometimes, while working with Python domain, we can have a problem in which we need to produce various combination of elements. This can be K sized unique combinations till N. This problem can have application in data domains and school programming. Let's discuss certain ways in which this task can be performed. Input : N = 2, K = 3 Output : [(0, 0
4 min read
Python program to get all pairwise combinations from a list
Given a list. The task is to write a Python program to get all pairwise combinations from the list. Finding all Pairs (No uniqueness) Example: Input: [1,"Mallika",2,"Yash"] Output: [(1, 'Mallika'), (1, 2), (1, 'Yash'), ('Mallika', 1), ('Mallika', 2), ('Mallika', 'Yash'), (2, 1), (2, 'Mallika'), (2, 'Yash'), ('Yash', 1), ('Yash', 'Mallika'), ('Yash'
4 min read
Python - Get all numbers combinations in list
Sometimes, while working with Python lists, we can have a problem in which we need to concatenate each number with other create new number. This kind of problem is peculiar but can have application in many domains such as day-day programming and gaming. Let's discuss certain ways in which this task can be performed. Input : test_list = [7, 3, 4, 5]
3 min read
Python - Dictionary Key Value lists combinations
Given a dictionary with values as a list, extract all the possible combinations, both cross keys and with values. Input : test_dict = {"Gfg" : [4, 5], "is" : [1, 2], "Best" : [9, 4]} Output : {0: [['Gfg', 4], ['is', 1], ['Best', 9]], 1: [['Gfg', 4], ['is', 1], ['Best', 4]], 2: [['Gfg', 4], ['is', 2], ['Best', 9]], 3: [['Gfg', 4], ['is', 2], ['Best'
9 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python Program to get all unique keys from a List of Dictionaries
Given a list arr[] consisting of N dictionaries, the task is to find the sum of unique keys from the given list of the dictionary. Examples: Input: arr = [{'my': 1, 'name': 2}, {'is': 1, 'my': 3}, {'ria': 2}]Output: ['ria', 'my', 'is', 'name']Explanation: The set of unique keys are {"ria", "my", "Is", "name"}. Input: arr = [{'X': 100, 'Y': 2}, {'Z'
4 min read
Python Program to print all Possible Combinations from the three Digits
Given 3 digits a, b, and c. The task is to find all the possible combinations from these digits. Examples: Input: [1, 2, 3] Output: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Input: [0, 9, 5] Output: 0 9 5 0 5 9 9 0 5 9 5 0 5 0 9 5 9 0 Method 1: Brute force or Naive approach The naive approach is to run 3 loops from 0 to 3 and print all the numbers from t
2 min read
Python program to find all the Combinations in the list with the given condition
Given a list with some elements being a list of optional elements. The task is to find all the possible combinations from all options. Examples: Input: test_list = [1,2,3] Output: [1], [1, 2], [1, 2, 3], [1, 3] [2], [2, 3], [3] Example 1: Get all possible combinations of a list’s elements using combinations C/C++ Code from itertools import combinat
3 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read