Search code examples
pythonformatoutputpython-itertools

Python specific format output with itertools.product


I am trying with a code as given below .

import itertools
f=[[0], [2], [3]]
e=[['x']if f[j][0]==0 else range(f[j][0]) for j in range(len(f))]
print(e)
List1_=[]
for i in itertools.product(e):
  List1_.append(i)
print(List1_)

I am expecting a result like given below

[('x', 0, 0), ('x', 0, 1), ('x', 1, 0), ('x', 1, 1), ('x', 2, 0), ('x', 2,1)]

but I am getting output as

[(['x'],), ([0, 1],), ([0, 1, 2],)]


Solution

  • You can use itertools.product:

    >>> from itertools import product
    >>> list(product(range(3), range(4)))
    [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
    >>>
    >>> def print_array(l):
    ...     for p in product(*map(range, l)):
    ...         print p
    ... 
    >>> print_array([3, 4])
    (0, 0)
    (0, 1)
    (0, 2)
    [...]
    

    Here is a little bit of explanation on why your program doesn't work as expected. Rather than a list of iterables, product takes a variable number of arguments. You can unpack a list into arguments for a function using the star *:

    e = [['x'], [0, 1], [0, 1, 2]]
    product(e)   # won't work
    product(e[0], e[1], e[2])   # ok when e's length is exactly 3
    product(*e)   # works for any e -> equivalent to product(e[0], e[1], ....)