Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 940
Amperclock Avatar asked Jan 01 '26 13:01

Amperclock


1 Answers

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):
    ...
like image 50
Jean-Paul Calderone Avatar answered Jan 03 '26 02:01

Jean-Paul Calderone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!