We are given a list and our task is to generate all possible pairs from the list. Each pair consists of two distinct elements from the list. For example: a = [1, 2, 3] then the output will be [(1,2), (1,3), (2,3)].
Using combinations() from itertools
combinations() function from the itertools module generates all possible pairs without repetition efficiently.
from itertools import combinations
a = [1, 2, 3]
res = list(combinations(a, 2))
print(res)
Output
[(1, 2), (1, 3), (2, 3)]
Explanation:
- combinations(a, 2) generates all unique pairs from a.
- list(...) converts the result into a list of tuples.
Using List Comprehension
List comprehension provides a more concise way to generate all possible pairs.
a = [1, 2, 3]
res = [(a[i], a[j]) for i in range(len(a)) for j in range(i + 1, len(a))]
print(res)
Output
[(1, 2), (1, 3), (2, 3)]
Explanation: This is a compact version of the nested loop method, the outer loop selects a[i] and the inner loop selects a[j], ensuring i < j.
Using Nested Loops
A simple way to generate all possible pairs is by using two nested loops.
a = [1, 2, 3]
res = []
for i in range(len(a)):
for j in range(i + 1, len(a)):
res.append((a[i], a[j]))
print(res)
Output
[(1, 2), (1, 3), (2, 3)]
Explanation: The outer loop picks an element a[i] and the inner loop picks elements a[j] (where j > i) to ensure unique pairs.
Using zip() with Slicing
We can use zip() along with slicing to generate pairs although this method is not recommended for general cases.
a = [1, 2, 3]
res = [(x, y) for i, x in enumerate(a) for y in a[i + 1:]]
print(res)
Output
[(1, 2), (1, 3), (2, 3)]
Explanation:
- enumerate(a) iterates with index i and value x.
- a[i + 1:] gives the remaining elements to form pairs.