
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Split tuple into groups of n in Python
- Python Program to Split a List into Two Halves
- Convert a list into tuple of lists in Python
- How to convert a list into a tuple in Python?
- Python program to count Bidirectional Tuple Pairs
- How do you split a list into evenly sized chunks in Python?
- Python program to convert Set into Tuple and Tuple into Set
- Custom list split in Python
- Find Maximum difference between tuple pairs in Python
- Flatten tuple of List to tuple in Python
- Count occurrence of all elements of list in a tuple in Python
- Java Program to Split a list into Two Halves
- Python Grouped summation of tuple list¶
- Python – Cross Pairing in Tuple List
- Extract digits from Tuple list Python

Advertisements