Reputation: 21223
Given a list l=range(n)
, how can I iterate over all distinct pairs of distinct pairs from that list.
For example, if l = [0,1,2,3]
I would like [((0,1), (0,2)),((0,1),(0,3)), ((0,1),(1,2)), ((0,1), (1,3)),((0,1), (2,3)), ((0,2), (0,3)), ((0,2),(1,2)),((0,2),(1,3)),((0,2),(2,3))...
Upvotes: 1
Views: 163
Reputation: 122024
You can use itertools.combinations
:
from itertools import combinations
for pair in combinations(combinations(l, 2), 2):
# use pair
The first call creates the initial pairs:
>>> l = [0,1,2,3]
>>> list(combinations(l, 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
The second pairs them again:
>>> list(combinations(combinations(l, 2), 2))
[((0, 1), (0, 2)), ((0, 1), (0, 3)), ((0, 1), (1, 2)), ((0, 1), (1, 3)),
((0, 1), (2, 3)), ((0, 2), (0, 3)), ((0, 2), (1, 2)), ((0, 2), (1, 3)),
((0, 2), (2, 3)), ((0, 3), (1, 2)), ((0, 3), (1, 3)), ((0, 3), (2, 3)),
((1, 2), (1, 3)), ((1, 2), (2, 3)), ((1, 3), (2, 3))]
Upvotes: 7