Francis1984
Francis1984

Reputation: 47

Multiple index loop in Python

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.

Upvotes: 0

Views: 894

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24052

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.

Upvotes: 3

Related Questions