- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Split list into all possible tuple pairs
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
Below is a demonstration of the same
def determine_pairings(my_list): if len(my_list) <= 1: return [my_list] result = [[my_list] + element for element in determine_pairings(my_list[1:])] for index in range(1, len(my_list)): result.extend([[(my_list, 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)
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)]]
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.
- Split tuple into groups of n in Python
- Convert a list into a tuple in Python.
- Convert a list into tuple of lists in Python
- How to convert a list into a tuple in Python?
- Python program to convert Set into Tuple and Tuple into Set
- Python program to count Bidirectional Tuple Pairs
- How do you split a list into evenly sized chunks in Python?
- Custom list split in Python
- Find Maximum difference between tuple pairs in Python
- Java Program to Split a list into Two Halves
- Flatten tuple of List to tuple in Python
- Python - Total equal pairs in List
- Count occurrence of all elements of list in a tuple in Python
- How can I append a tuple into another tuple in Python?
- How to split Python tuples into sub-tuples?