Search code examples
pythonpython-3.xpython-itertools

Python - Dynamically change number of arguments


I want to calculate a cartesian product from a changing number of sets.

The cartesian product can be computed using itertools.product(*args, repeat=1)

itertools.product(set1, set2, repeat=1)

but the number of sets is actually unknown, it depends on the data. Sometimes it might be 2 groups, sometimes 3 or more.

Is there a way to submit *args such that it can dynamically change the number of arguments?

myargs = [set1, set2, set3]
itertools.product(myargs,repeat=1)

Solution

  • Yes, there is such a way. Use the * argument expansion operator:

    myargs = [set1, set2, set3]
    itertools.product(*myargs,repeat=1)
    

    Reference: