54

Edit: This is not a exact duplicate of How to get all possible combinations of a list’s elements?

This topic is about finding unique combinations while the other topic is about finding ALL combinations.

If I have a python list:

 L = [1,2,3,4]

what's the best way to get all the possible unique combinations of 3 elements from the list like below:

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

The order of the elements in the combinations doesn't matter. For example, "1,2,3" and "3,2,1" will be considered the same combination.

I can probably write a few loops to do this but I think there might be a one-liner which can do the same.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Allen Qin
  • 19,507
  • 8
  • 51
  • 67
  • This question should not originally have been closed as a duplicate in the way that it was, or at least it should have been reopened. However, it *has* been asked more than once on Stack Overflow. I have re-linked it as a different duplicate, because that question got higher-quality answers. – Karl Knechtel Feb 28 '23 at 19:54

1 Answers1

74

You need itertools.combinations:

>>> from itertools import combinations
>>> L = [1, 2, 3, 4]
>>> [",".join(map(str, comb)) for comb in combinations(L, 3)]
['1,2,3', '1,2,4', '1,3,4', '2,3,4']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 6
    Interestingly, this does give you unique combinations based on positions in the iterable, not based on values, as explained in the docs, see e.g.: from itertools import combinations L = [1, 2, 3, 4, 4] [",".join(map(str, comb)) for comb in combinations(L, 3)] – mloning Nov 28 '18 at 14:59