When it is required to get all pairwise combinations from a list, an iteration along with the ‘append’ method is used.
Example
Below is a demonstration of the same
my_list = [15,"John", 2, "Will", 53, 'Rob'] print("The list is :") print(my_list) my_result = [] for i in range(0,len(my_list)): for j in range(0,len(my_list)): if (i!=j): my_result.append((my_list[i],my_list[j])) print("The result is :") print(my_result)
Output
The list is : [15, 'John', 2, 'Will', 53, 'Rob'] The result is : [(15, 'John'), (15, 2), (15, 'Will'), (15, 53), (15, 'Rob'), ('John', 15), ('John', 2), ('John', 'Will'), ('John', 53), ('John', 'Rob'), (2, 15), (2, 'John'), (2, 'Will'), (2, 53), (2, 'Rob'), ('Will', 15), ('Will', 'John'), ('Will', 2), ('Will', 53), ('Will', 'Rob'), (53, 15), (53, 'John'), (53, 2), (53, 'Will'), (53, 'Rob'), ('Rob', 15), ('Rob', 'John'), ('Rob', 2), ('Rob', 'Will'), ('Rob', 53)]
Explanation
A list is defined and is displayed on the console.
An empty list is defined.
The original list is iterated over, and again iterated over using two iterations in all.
When both the indices are not equal, the respective elements of the list are appended to the empty list.
This is the result which is displayed as output on the console.