2

Let's say I have a list of four values. I want to find all combinations of two of the values. For example, I would like to get an output like:

((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3))

As you can see, I do not want repetitions, for example (0, 1) and (1, 0)

This needs to be able to be used with larger numbers, not just 4, and I will have to iterate through all of the combos

I am using Python 3 and Windows, and this would ideally be an inbuilt function, a simple bit of list comprehension code, or something I can import. I have tried making this with range, but I do not know how to exclude the numbers that I have already done from it.

martineau
  • 119,623
  • 25
  • 170
  • 301
John Andleson
  • 37
  • 1
  • 2
  • 3
    take a look at [combinations from itertools](https://docs.python.org/3/library/itertools.html#itertools.combinations) – Ma0 Jun 08 '18 at 06:38
  • Ok sure, but did you give a chance to actually search for this problem in advance or do you assume the question is new? Do you have problems with a specific line in your code? `from itertools import combinations` and `for i in combinations(range(4),2): print(i)` would be enough to create a generator and loop it. – Anton vBR Jun 08 '18 at 06:39
  • @PatrickArtner I agree. However I did not find any good explaining answer to this question. It might be that the basics of it is already well-documented. – Anton vBR Jun 08 '18 at 06:44

2 Answers2

11

It is very easy

from itertools import combinations
list(combinations([0,1,2,3],2))
aman5319
  • 662
  • 5
  • 16
3

Take just the lower triangular matrix if you only need a distinct set

a = [1,2,10,20]
[(a[i], a[j+i+1]) for i in range(len(a))  for j in range(len(a[i+1:]))]

[(1, 2), (1, 10), (1, 20), (2, 10), (2, 20), (10, 20)]
MaxS
  • 31
  • 3