Home > Enterprise >  How do I create nested for loops inside a function?
How do I create nested for loops inside a function?

Time:02-18

I am trying to create a function that will take an input x and create x nested for loops. Here's an example:

def looper(loop_amount, loop_value):
    for n in range(loop_amount):
        # Create a nested loop with loop_value.

looper(3, 5)

# Creates this:
for n in range(5):
    for n in range(5):
        for n in range(5):

CodePudding user response:

You can use the itertools module

import itertools

for tup in itertools.product(*(range(loop_value) for _ in range(loop_amount))):
    # tup is a tuple of length loop_amount which will contain 
    # every combination of numbers between 0 and loop_value-1

CodePudding user response:

You are very close, hope this helps.

def loop(value):
    for n in range(value):
       

def looper(loop_amount, loop_value):
    for n in range(loop_amount):
        loop(loop_value)

CodePudding user response:

A possible (though maybe non-pythonic) solution is to use recursion:

def looper(loop_amount, loop_value):
    if loop_value == 0:
        # Code to be run in innermost loop
    else:
        for n in range(loop_amount):
            looper(loop_value - 1)

This can be extended to access each loop's index, or have a return value in some fashion.

  • Related