Open In App

Python – All possible pairs in List

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python list, we can have a problem in which we need to extract all the possible pairs that can be performed from integers from list. This kind of problem can occur in many domains such as day-day programming and web development. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [1, 7, 4] 
Output : [(1, 7), (1, 4), (7, 4)] 

Input : test_list = [7, 4] 
Output : [(7, 4)]

Method #1 : Using list comprehension + enumerate() This is one of the ways in which this task can be performed. In this, we perform the task of pairing using nested loops in list comprehension recipe, and enumerate() is used to check with the next indices while iteration. 

Python3




# Python3 code to demonstrate working of 
# All possible pairs in List
# Using list comprehension + enumerate()
 
# initializing list
test_list = [1, 7, 4, 3]
 
# printing original list 
print("The original list : " + str(test_list))
 
# All possible pairs in List
# Using list comprehension + enumerate()
res = [(a, b) for idx, a in enumerate(test_list) for b in test_list[idx + 1:]]
 
# printing result 
print("All possible pairs : " + str(res))


Output

The original list : [1, 7, 4, 3]
All possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]

Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(n^2), due to the list comprehension creating a new list of all possible pairs.

Method #2: Using combinations() This is one of the ways in which this task can be performed. In this, we just using inbuilt function for pairing and sending 2 as value for making pairs of size 2. 

Python3




# Python3 code to demonstrate working of
# All possible pairs in List
# Using combinations()
from itertools import combinations
 
# initializing list
test_list = [1, 7, 4, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# All possible pairs in List
# Using combinations()
res = list(combinations(test_list, 2))
 
# printing result
print("All possible pairs : " + str(res))


Output : 

The original list : [1, 7, 4, 3]
All possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]

Time Complexity: O(n^2) .
Auxiliary Space: O(n^2).

Method #3: Using nested loops

In this approach, we can use nested loops to iterate through each element in the list and form pairs. We can then append each pair to a new list and return it as the result.

step-by-step approach

  1. Define a list called test_list containing some integer values.
  2. Print the original list using the print() function.
  3. Create an empty list called res. This list will hold all the possible pairs.
  4. Determine the length of the test_list using the len() function and store it in a variable called n.
  5. Use a nested loop structure to generate all the possible pairs of elements in the test_list. The outer loop will iterate over the elements in the list starting from the first element, and the inner loop will iterate over the remaining elements in the list starting from the next element.
  6. In each iteration of the loop, append a tuple containing the current pair of elements to the res list.
  7. Print the result list using the print() function.
  8. I hope this helps!

Python3




# Python3 code to demonstrate working of
# All possible pairs in List
# Using nested loops
 
# initializing list
test_list = [1, 7, 4, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# All possible pairs in List
# Using nested loops
res = []
n = len(test_list)
for i in range(n):
    for j in range(i+1, n):
        res.append((test_list[i], test_list[j]))
 
# printing result
print("All possible pairs : " + str(res))


Output

The original list : [1, 7, 4, 3]
All possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]

Time complexity: O(n^2), where n is the length of the list.

Auxiliary space: O(n^2), as we need to store all possible pairs in the result list.

METHOD 4:Using recursion

APPROACH:

The program finds all possible pairs of elements in a given list and returns the pairs as a list

ALGORITHM:

  1. Define a function called “all_pairs” that takes a list as input.
  2. If the length of the list is less than or equal to 1, return an empty list.
  3. Create an empty list called “pairs”.
  4. For each element in the list, except the first element, create a tuple of that element and the first element.
  5. Append the tuple to the “pairs” list.
  6. Recursively call the “all_pairs” function with the list starting from the second element.
  7. Return the concatenation of the “pairs” list and the result of the recursive call to “all_pairs” function.

Python3




# Python program for the above approach
 
# Function to find all pairs
def all_pairs(lst):
    if len(lst) <= 1:
        return []
     
    pairs = [(lst[0], x) for x in lst[1:]]
     
    return pairs + all_pairs(lst[1:])
   
# Driver Code
lst = [1, 7, 4, 3]
pairs = all_pairs(lst)
 
print("All possible pairs:", pairs)


Output

All possible pairs: [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]

Time Complexity:
The time complexity of this algorithm is O(n^2), where n is the length of the input list. This is because for each element in the list, the algorithm has to create a tuple with every other element in the list except itself.

Space Complexity:
The space complexity of this algorithm is O(n^2), where n is the length of the input list. This is because the algorithm creates a list of tuples, each containing two elements, for every pair of elements in the input list.

METHOD 5:Using re module.

APPROACH:

This program uses the re module to extract integers from the given input string, and then generates all possible pairs of those integers using a list comprehension. The pairs are then printed as output.

ALGORITHM:

1.Import the re module.
2.Define the input string.
3.Use re.findall() function to extract all integers from the input string and convert them to a list of integers using a list comprehension.
4.Use nested loops to generate all possible pairs of integers from the list.
5.Store the pairs in a list.
6.Print the list of pairs.

Python3




import re
 
input_string = "The original list : [1, 7, 4, 3]"
integers = [int(num) for num in re.findall(r'\d+', input_string)]
pairs = [(integers[i], integers[j]) for i in range(len(integers))
         for j in range(i+1, len(integers))]
 
print("All possible pairs:", pairs)


Output

All possible pairs: [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]

Time complexity: O(n^2)
Auxiliary Space: O(n)



Last Updated : 18 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads