Python print every unique combination of list items

Question:

What is the cleanest (most "pythonic") way of printing every unique combination of three items in the following list?

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

The solution needs to avoid duplicates:

1 and 1 and 1 No (not unique)
1 and 1 and 2 No (not unique)
1 and 1 and 3 No (not unique)
...
1 and 2 and 3 Yes
1 and 2 and 4 Yes
1 and 3 and 1 No (not unique)
1 and 3 and 2 No (occurred previously)
...

I am using numbers here just for clarity, the actual project involve text strings and there are 24 of them, but the same logic should apply.

Here is my first attempt:

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

for a in strats:
    for b in strats:
        for c in strats:
            if a != b and a != c and b!=c:
                print(a+" and "+b+" and "+c)

The problem with the output is that it contains duplicates:

1 and 2 and 3 Fine
1 and 2 and 4 Fine
1 and 3 and 2 Duplicate
1 and 3 and 4 Fine
1 and 4 and 2 Duplicate
1 and 4 and 3 Duplicate
...
Asked By: Ned Hulton

||

Answers:

Python has built-in support for permutations and combinations. This will print out all the unique sets of 3 from a universe of N items:

import itertools
for nxt in itertools.combinations(strats, 3):
   print(nxt)

There are 2,024 ways of taking 3 items from a population of 24.

Answered By: Tim Roberts
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.