Search code examples
pythonpython-itertoolscombinatorics

List of lists to iterables in itertools


I would like to use itertools.product. The documentations specifies itertools.product(*iterables, repeat=1). For example this

for i in itertools.product([1,3,4],[2,3,6],[9,4]):
    print(i)

Outputs

(1, 2, 9)
(1, 2, 4)
(1, 3, 9)
(1, 3, 4)
(1, 6, 9)
(1, 6, 4)
(3, 2, 9)
(3, 2, 4)
(3, 3, 9)
(3, 3, 4)
(3, 6, 9)
(3, 6, 4)
(4, 2, 9)
(4, 2, 4)
(4, 3, 9)
(4, 3, 4)
(4, 6, 9)
(4, 6, 4)

My problem is that I don't have a fixed number of such lists but a variables one as a list of lists (e.g. [[1,3,4],[2,3,6],[9,4]]).

I would like to transform this list of lists as iterables that I can pass to itertools.product.

Bonus point. Acutally what I have isn't a list of lists but it is a dictionary which values are lists. So if I can avoid converting it to a list of lists it's even better.


Solution

  • i think this is what you want:

    import itertools
    
    lists = [[1, 3, 4], [2, 3, 6], [9, 4]]
    for i in itertools.product(*lists):
        print(i)
    

    Output:

    (1, 2, 9)
    (1, 2, 4)
    (1, 3, 9)
    (1, 3, 4)
    (1, 6, 9)
    (1, 6, 4)
    (3, 2, 9)
    (3, 2, 4)
    (3, 3, 9)
    (3, 3, 4)
    (3, 6, 9)
    (3, 6, 4)
    (4, 2, 9)
    (4, 2, 4)
    (4, 3, 9)
    (4, 3, 4)
    (4, 6, 9)
    (4, 6, 4)