Search code examples
pythonloopsnested-loops

Nested loops with depth parameter in python


How do I make a number of nested loops where depth is a parameter. I am thinking of a function which takes depth as a parameter

def make_nested_loops(depth):
    ...

And, the result for depth=3 is the following

for i1 in range(10):
    for i2 in range(i1 + 1, 10):
        for i3 in range(i2 + 1, 10):
            # do stuff

So far I've been able to do this using strings building and exec command. But I think there is better and more efficient way to do it.


Solution

  • An inefficient but simple approach would be to use itertools.product and filter unwanted tuples:

    def make_tuples(depth, n):
        for i in itertools.product(range(n), repeat=depth):
            if sorted(i) < i:
                continue
            yield i
    

    More efficient would be a recursive generator:

    def make_tuples(depth, n, start=0):
        if depth == 0:
            yield ()
        else:
            for x in range(start, n):
                for t in make_tuples(depth - 1, n, x + 1):
                    yield (x,) + t
    

    Using it would look like

    for (i1, i2, i3) in make_tuples(3, 10):
        # do stuff with i1, i2, i3
    

    If the depth is really dynamic, you can't of course unpack the tuples coming from make_tuples. The body will have to know what to do with tuples of fixed but unknown length.

    for tpl in make_tuples(n, 10):
        # Do stuff with tpl