Skip to content Skip to sidebar Skip to footer

Python: Dynamic Nested For Loops Each With Different Range

I want to create a code that can iterate over a dynamic number (N) of nested loops each with different range. For example: N=3 ranges=[[-3, -2, -1, 0, 1, 2, 3], [-5, -4, -3, -2,

Solution 1:

Your code is equivalent to itertools.product:

print(list(itertools.product(*ranges)))

Solution 2:

So, if I am understanding your question correctly, you want the values being iterated over to be [-3, -5, -3], [-2, -4, -2].... This can be accomplished easily with zip function built into python:

for x inzip(*ranges):
    # Do something with x

x will take on a tuple of all the first values, then a tuple of all the second values, etc, stopping when the shortest list ends. Using this * splat notation avoids even having to know about the number of lists being combined.

Post a Comment for "Python: Dynamic Nested For Loops Each With Different Range"