How to apply itertools.product to elements of a list of lists? How to apply itertools.product to elements of a list of lists? python python

How to apply itertools.product to elements of a list of lists?


>>> list(itertools.product(*arrays))[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]

This will feed all the pairs as separate arguments to product, which will then give you the cartesian product of them.

The reason your version isn't working is that you are giving product only one argument. Asking for a cartesian product of one list is a trivial case, and returns a list containing only one element (the list given as argument).


>>> arrays = [(-1,+1), (-2,+2), (-3,+3)]>>> list(itertools.product(*arrays))[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]


you can do it in three rurch using itertools.product

lst=[]arrays = [(-1,+1), (-2,+2), (-3,+3)]  import itertools for i in itertools.product(*arrays):         lst.append(i)print(lst)

enter image description here