Python - Split list into all possible tuple pairs

PythonServer Side ProgrammingProgramming

When it is required to split the list into all the possible tuple pairs, a method can be defined that takes a list as a parameter and uses list comprehension to iterate through the list and use ‘extend’ method

Example

Below is a demonstration of the same

def determine_pairings(my_list):
   if len(my_list) <= 1:
      return [my_list]
   result = [[my_list[0]] + element for element in determine_pairings(my_list[1:])]
   for index in range(1, len(my_list)):
      result.extend([[(my_list[0], my_list[index])] + element for element in determine_pairings(my_list[1: index] + my_list[index + 1:])])

   return result

my_list = [56, 31, 78, 0]

print("The list is :")
print(my_list)

my_result = determine_pairings(my_list)

print("The resultant pairs are :")
print(my_result)

Output

The list is :
[56, 31, 78, 0]
The resultant pairs are :
[[56, 31, 78, 0], [56, 31, (78, 0)], [56, (31, 78), 0], [56, (31, 0), 78], [(56, 31), 78, 0], [(56, 31), (78, 0)], [(56, 78), 31, 0], [(56, 78), (31, 0)], [(56, 0), 31, 78], [(56, 0), (31, 78)]]

Explanation

  • A method named ‘determine_pairings’ is defined that takes a list as a parameter.

  • The length of the list is checked to be greater than 1.

  • The elements excluding the firs element is considered and the method is called again.

  • This is assigned to a variable.

  • The list is iterated over again, and the first element and the index element is added to the variable.

  • This is returned as output.

raja
Published on 20-Sep-2021 11:26:05
Advertisements