0

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, -1, 0, 1, 2, 3, 4, 5],
  [-3, -2, -1, 0, 1, 2, 3]]

for x in ranges[0]:
    for y in ranges[1]:
        for z in range[2]:
            variable=[x, y, z]

Im new to python. As I went over similar questions posted here I have the understanding that this can be done with recursion or itertools. However, none of the answers posted solve this problem for a different range at each level. The closest posted question similar to mine was Variable number of nested for loops with fixed range . However, the answer posted by user633183 is coded in python 3.X and I am coding in python 2.7 so I couldn't implement it as some of its code does not work on python 2.7. Can you please help me to code this problem. Thanks!

PJORR
  • 71
  • 5
  • 2
    You will get more and better answers if you create a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example. Especially make sure that the input and expected test data are complete (not pseudo-data), and can be easily cut and and paste into an editor to allow testing proposed solutions. – Stephen Rauch Jun 01 '18 at 05:05
  • Possible duplicate of [Iterating over a 2 dimensional python list](https://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list) – Anand Tripathi Jun 01 '18 at 05:24

2 Answers2

1

Your code is equivalent to itertools.product:

print(list(itertools.product(*ranges)))
Austin
  • 25,759
  • 4
  • 25
  • 48
  • Thanks. I used this code v=list(itertools.product(*ranges)) for i in range(len(v)): var=v[i] do Something with var – PJORR Jun 01 '18 at 05:32
1

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 in zip(*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.

BowlingHawk95
  • 1,518
  • 10
  • 15