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!

2
  • 2
    You will get more and better answers if you create a Minimal, Complete, and Verifiable 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. Commented Jun 1, 2018 at 5:05
  • Possible duplicate of Iterating over a 2 dimensional python list Commented Jun 1, 2018 at 5:24

2 Answers 2

1

Your code is equivalent to itertools.product:

print(list(itertools.product(*ranges)))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I used this code v=list(itertools.product(*ranges)) for i in range(len(v)): var=v[i] do Something with var
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.