4

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?

areedy
  • 117
  • 4
  • I understand that it returns ones on different positions, is it possible to get around this? – areedy Sep 03 '21 at 20:42
  • 1
    Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Dennis Kozevnikoff Sep 03 '21 at 20:43
  • 3
    You want [(unique) `permutations`](https://stackoverflow.com/q/6284396/1639625), not `combinations` or`product`. – tobias_k Sep 03 '21 at 20:44
  • 1
    [multiset_permutations](https://docs.sympy.org/latest/modules/utilities/iterables.html?highlight=multiset_permutations#sympy.utilities.iterables.multiset_permutations) gives the non-repeating permutations – Chris Charley Sep 03 '21 at 21:36

1 Answers1

7

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)]
MohitC
  • 4,541
  • 2
  • 34
  • 55