I've referenced this question How to generate all permutations of a list in Python, where I faced a similar scenario that expressed in this question.
This time, I wanna generate all possible permutations(without an empty list []
)of a list , and store it in another single list. E.g. the target list is a_list=[1, 2, 3]
, and I want something like:
[
[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]
]
I've tried this code, which worked successfully (using built-in itertools
module):
import itertools
perm = list()
for i in range(1, len(a_list) + 1):
perm.extend([list(x) for x in itertools.permutations(a_list, i)])
I wanna to try it in a list comprehension way, but I failed with this attempt:
perm = [list(x) for x in permutations(a_list, i) for i in range(1, len(a_list)+1)]
So is there any feasible list comprehension method to do this stuff?