Get all pairwise combinations from a list

Utsav Vakil picture Utsav Vakil · Oct 17, 2016 · Viewed 13.7k times · Source

For example, if the input list is

[1, 2, 3, 4]

I want the output to be

[[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]

If possible, I would like a solution which is better than the brute force method of using two for loops. How do I implement this?

Answer

brianpck picture brianpck · Oct 17, 2016

Though the previous answer will give you all pairwise orderings, the example expected result seems to imply that you want all unordered pairs.

This can be done with itertools.combinations:

>>> import itertools
>>> x = [1,2,3,4]
>>> list(itertools.combinations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

Compare to the other result:

>>> list(itertools.permutations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]