Allen - 5 months ago 31

Python Question

Edit:

This is not a exact duplicate of Python code to pick out all possible combinations from a list?

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

`["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"`

`"3,2,1"`

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

Answer

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']
```