Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all pairwise combinations from a list

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?

like image 908
Utsav Vakil Avatar asked Oct 17 '16 17:10

Utsav Vakil


People also ask

How do you get all the unique combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

What is pairwise Python?

The pairwise() method in the itertools module returns the successive overlapping pairs taken from the input iterable. The sequence of the output pairs is in the order of the elements in the iterable. This functionality was introduced in Python version 3.10.


2 Answers

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)]
like image 89
brianpck Avatar answered Oct 22 '22 21:10

brianpck


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))
like image 21
MooingRawr Avatar answered Oct 22 '22 23:10

MooingRawr