0

I have the following lists:

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

From the above, I would like to generate a list containing:

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

What is this process called?

Generate a factorial of python lists?

Is there a built-in library that does this?

allprog
  • 16,540
  • 9
  • 56
  • 97
I Love Python
  • 862
  • 2
  • 13
  • 20

4 Answers4

5

Using itertools.product:

>>> import itertools
>>> [list(xs) for xs in itertools.product([1,2,3], [1], [1,2,3,4])]
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]]
falsetru
  • 357,413
  • 63
  • 732
  • 636
3

itertools.product

>>> lists = [[1,2,3], [1], [1,2,3,4]]  
>>> from itertools import product
>>> map(list, product(*lists))
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]]

Note: the usage of map allows me to convert the otherwise tuple results of product's iteration into lists easily.

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
2
inputList = [[1,2,3], [1], [1,2,3,4]]

import itertools
print [list(item) for item in itertools.product(*inputList)]

Output

[[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 1, 4],
[2, 1, 1],
[2, 1, 2],
[2, 1, 3],
[2, 1, 4],
[3, 1, 1],
[3, 1, 2],
[3, 1, 3],
[3, 1, 4]]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

As suggested in the other answers itertools.product is the way to go here, but for completeness and as an illustration of what itertools.product does here is a solution using a list comprehension:

result = [[x,y,z] for x in [1,2,3] for y in [1] for z in [1,2,3,4]]

Here is the same thing using normal for loops which may make it a bit more readable:

result = []
for x in [1,2,3]:
    for y in [1]:
        for z in [1,2,3,4]:
            result.append([x, y, z])
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306