0

I need to make several nested loops like this, but with a generic number of looping indices:

   for ii in range(0,num):
      for iii in range(0,num):
         for iiii in range(0,num):
            for iiiii in range(0,num):

Is it there any compact or practical way to do this? Thanks in advance.

3
  • I am unclear what you need to do and why. Could you explain it in a bit more detail? edit your minimal reproducible example. Commented Jun 14, 2021 at 13:11
  • use set product instead, Take a look at 'set theory' , you will find set product. you can use that to generate one list and you can iterate through that with right interval Commented Jun 14, 2021 at 13:11
  • 1
    Search for python cartesian product. Commented Jun 14, 2021 at 13:15

1 Answer 1

3

Use itertools.product to generate tuples of the desired indices. For example:

import itertools
for indices in intertools.product(range(num), repeat=depth):
    print(indices)

This will generate tuples of length depth of the values.

Here's a small example:

>>> for indices in itertools.product(range(3), repeat=2):
...     print(indices)
... 
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
>>> 

In this example, the number of values present in each tuple is 2, given by repeat=2.

Sign up to request clarification or add additional context in comments.

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.