Jeremy Thomas
Jeremy Thomas

Reputation: 6694

Get permutations of lists using python

Let's assume I have list a:

a = [0, 0, [0, 1], [0, 1, 2]]

where a can be of any length, and its constituents can be of any length and I want to generate a new list that can be any combination of the values such that for the given example I would return:

b = [[0,0,0,0],
     [0,0,0,1],
     [0,0,0,2], 
     [0,0,1,0],
     [0,0,1,1],
     [0,0,1,2]]

I think it's just a matter of looping, but I would appreciate any help.

Thanks

Upvotes: 1

Views: 71

Answers (1)

falsetru
falsetru

Reputation: 369444

Using itertools.product:

>>> import itertools
>>> a = [0, 0, [0, 1], [0, 1, 2]]
>>> a2 = [x if isinstance(x, list) else [x] for x in a]
>>> #  = [[0], [0], [0, 1], [0, 1, 2]]
>>> list(itertools.product(*a2))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 1, 0), (0, 0, 1, 1), (0, 0, 1, 2)]

Upvotes: 4

Related Questions