4

Say I had a list: [1,2,3]

How would I generate:

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

I know how to use itertools.permutations(), but I don't know how to generate this portion [1],[2],[3],[1,2],[1,3],[2,3] of the list.

Thanks!

1
  • 4
    Are you deliberately excluding permutations such as [2,1], [3,1], [3,2]? Commented Dec 8, 2014 at 2:50

2 Answers 2

2

Your expected result does not contain all possible permutations, so not sure this is what you want, or you missed some. But to get all possible permutations of a list of different lengths, you can do as follows:

from itertools import permutations
a_list = [1,2,3]
perm_list = [p for l in range(1, len(a_list)+1) for p in permutations(a_list,l)]
print(perm_list)

The result is:

[(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

If the input list is large though, probably it would be better to use generator expression, e.g.

perm_list_gen = (p for l in range(1, len(a_list)+1) for p in permutations(a_list,l))
print(perm_list_gen)
#prints:  <generator object <genexpr> at 0x7f176bbd88b8>

And than just go one by one, instead of everything at once:

for perm in perm_list_gen:
    print(perm)
Sign up to request clarification or add additional context in comments.

Comments

0
from itertools import permutations
lst = [1, 2, 3]
per = list(permutations(lst, 1)) + list(permutations(lst, 2)) + list(permutations(lst, 3))

output:

>>> [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.