Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently create nested loops and append the output (as a multi-dimensional array) from all the loops?

Tags:

python

I'm looking for an 'efficient' way in Python 3.x to create various nested loops, and then append the result of each inner loop (a multi-dimensional array).

For instance, the function model_A() has 3 parameters (a, b, c), and I want to enumerate all of the possibilities to test the model. The casual way is:

result_a = []
for a_value in a:
    result_a_b = []
    for b_value in b:
        result_a_b_c = []
        for c_value in c:
            result = model_A(a, b, c)
        result_a_b_c.append(result)
    result_a_b.append(result_a_b_c)
result_a.append(result_a_b)

I think there should be a way to 'efficiently' create the nested loop, and append the result, without having to create an empty list before each loop, and append the result at the end of each inner loop.

like image 226
lonelyhill Avatar asked Jan 30 '26 18:01

lonelyhill


1 Answers

Probably itertools.product() has what you need

for instance:

a = [1, 2]
b = [3, 4]
c = [5, 6]

for element in itertools.product(a,b,c):
    print(element)

Results in:

(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)

This might enable you to avoid the deeply nested for loops.

like image 56
Filipe Avatar answered Feb 02 '26 10:02

Filipe