0

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?

Sean_Syue
  • 555
  • 7
  • 14
  • 3
    You have the ordering of the loops the wrong way around... See e.g. https://stackoverflow.com/q/35479600/3001761, and please note that searching for the error message (which you should have included as part of a [mcve] in the question) would find you these answers. – jonrsharpe Jun 26 '18 at 08:14

1 Answers1

3

As the comments say, you have mixed up the order of the for loops. The first for is the outer loop, the second for is the inner loop (read left to right in a list comprehension).

This is the correct ordering:

import itertools   

a_list=[1, 2, 3]

perm = [list(x) for i in range(1, len(a_list)+1) for x in itertools.permutations(a_list, i)]

print(perm)

>>>[[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]]
iacob
  • 20,084
  • 6
  • 92
  • 119