goldisfine
goldisfine

Reputation: 4850

Generate all permutations of a list and permutations of the possible lists within that list?

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!

Upvotes: 4

Views: 73

Answers (2)

João Paulo
João Paulo

Reputation: 6670

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)]

Upvotes: 0

Marcin
Marcin

Reputation: 238051

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)

Upvotes: 2

Related Questions