Amperclock
Amperclock

Reputation: 409

Variable length nested loop Python

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

Upvotes: 3

Views: 1600

Answers (1)

Jean-Paul Calderone
Jean-Paul Calderone

Reputation: 48335

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):
    ...

Upvotes: 6

Related Questions