Radio Controlled
Radio Controlled

Reputation: 950

How to do a nested loop over a variable length list of generators?

I have a list of generators L = [gen_1,...,gen_n] with variable length n.

How can I implement in a compact way the following:

for el_1 in gen_1:
    for ...
        for el_n in gen_n:
            do_something([el_1,...,el_n])

That should be a fairly common problem, but somehow I can't figure it out and also could not find anything online so far.

Unlike in the simpler case of iterating over the Cartesian product over a list of generators as in this question, a variable-depth for loops allows to execute code at any level.

As an example problem, maybe we can assume the simple case of tracking the index of each loop's generator:

i_1 = 0
for el_1 in gen_1:
    i_1 += 1
    i_2 = 0
    for ...
        i_n = 0
        for el_n in gen_n:
            i_n += 1
            do_something([el_1,...,el_n],[i_1,...,i_n])

This is just an example of calling some code in a specific place in the nested for loop. Specific being bound by the length of the list of the generators.

Upvotes: 0

Views: 57

Answers (0)

Related Questions