Iterate over all combinations of values in multiple lists in Python [duplicate]

itertools.product should do the trick.

>>> import itertools
>>> list(itertools.product([1, 5, 8], [0.5, 4]))
[(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]

Note that itertools.product returns an iterator, so you don’t need to convert it into a list if you are only going to iterate over it once.

eg.

for x in itertools.product([1, 5, 8], [0.5, 4]):
    # do stuff

Leave a Comment