Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make n-dimensional nested for-loops in Python? [duplicate]

I have the following situation:

for x1 in range(x1, x2):
    for x2 in range(x3, x4):
        for x3 ...
            ...
                f(x1, x2, x3, ...)

How to convert this to a mechanism in which I only tell python to make n nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.

like image 440
JonathanGreszwinsky Avatar asked Jun 14 '18 15:06

JonathanGreszwinsky


People also ask

How do you combine nested loops in Python?

So to clarify the combine function would do something as follows: List1 = range(5) List2 = range(5) combine(List1, List2,) >>> (0,0) >>> (0,1) >>> (0,2) . . . >>> (2,4) >>> (3,0) . . .

Can for loops be nested inside one another?

A for loop can have more than one loop nested in it A for loop can have more than one loop nested in it.

Can you have multiple for loops in Python?

Nested For LoopsLoops can be nested in Python, as they can with other programming languages. The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion.

How many nested loops can you have in Python?

The outer loop can contain more than one inner loop. There is no limitation on the chaining of loops. In the nested loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop.


1 Answers

What you want to do is iterate over a product. Use itertools.product.

import itertools

ranges = [range(x1, x2), range(x3, x4), ...]

for xs in itertools.product(*ranges):
    f(*xs)

Example

import itertools

ranges = [range(0, 2), range(1, 3), range(2, 4)]

for xs in itertools.product(*ranges):
    print(*xs)

Output

0 1 2
0 1 3
0 2 2
0 2 3
1 1 2
1 1 3
1 2 2
1 2 3
like image 142
Olivier Melançon Avatar answered Oct 05 '22 23:10

Olivier Melançon