3

I'm trying to have a variable length nested for loop in python and to be able to reuse the variables.

for i in range(0,256):
    for j in range(0,256):
        for k in range(0,256):
            ...
            myvar[i][j][k]...

In the code above, there's a hard coded nested for loops with a length of 3 for.

It should work like this:

for index[0] in range(0,256):
  for index[1] in range(0,256):
    for index[2] in range(0,256):
      ...
        for index[n-1] in range(0,256):
          for index[n] in range(0,256):
            myvar[index[0]][index[1]][index[2]] ... [index[n-1]][index[n]] ...

for an arbitrary value of n

1
  • 1
    Don't know, but i'd say that if you need more than three nested loops you should approach the solution differently. Commented Mar 21, 2018 at 11:01

1 Answer 1

6

One approach is to have a single loop over permutations of your values.

Consider this behavior of itertools.product:

>>> list(product(*[range(3)] * 2))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

So you can get the same values as you would get from a bunch of nested loops in just one loop over the product of some iterators:

from itertools import product

number = 3
ranges = [range(256)] * number
for values in product(*ranges):
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

So the variable number represent the length/"depth" of my nest ?
let me check is this suite my needs :)

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.