15
votes

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?

2
There are 2^n pair-wise combinations for a collection of n elements. All solutions will require an exponential amount of time to generate all combinations; a nested for-loop is going to get you within a constant factor of the fastest solution. Unless you were simply looking for something more compact. - lungj
@lungj It's been a while since I've studied math formally, but where are you getting that 2^n figure? Ordered pairs are 4! / (4 - 2)! (== 12) and unordered pairs are 4 choose 2 (== 6) - brianpck
@brianpck Whoops. Yes, you're right. It's O(n^2). - lungj

2 Answers

34
votes

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)]
5
votes
import itertools

x = [1,2,3,4]

for each in itertools.permutations(x,2):
    print(each)

Note that itertools is a generator object, meaning you need to iterate through it to get all you want. The '2' is optional, but it tells the function what's the number per combination you want.

You can read more here

Edited:

As ForceBru said in the comment, you can unpack the generator to print, skipping the for loop together But I would still iterate through it as you might not know how big the generated object will be:

print(*itertools.permutations(x, 2))