Get all possible order combinations in python

Viewed 203

I have a list of 1 and 2, e.g. [2, 1, 1, 1] I need to get all possible combinations:

[[2, 1, 1, 1], 
[1, 2, 1, 1], 
[1, 1, 2, 1],
[1, 1, 1, 2]]

I tried to use itertools' product, however, it return the same result (e.g. [2, 1, 1, 1]) multiple times, and it is inefficient when input is bigger. Is there some build in function for something like this?

1 Answers

What you are looking for is permutations:

>>> import itertools
>>> a = [2, 1, 1, 1]
>>> list(set(itertools.permutations(a)))
[(1, 1, 1, 2), (1, 1, 2, 1), (2, 1, 1, 1), (1, 2, 1, 1)]
Related