Home > Blockchain >  Easier way to do nested for loops?
Easier way to do nested for loops?

Time:11-06

So in a lot of my coding problems, I end up doing something along the lines of:

for i in range(10):
    for j in range(10):
        for k in range(10):
            print(i, j, k)

I was just wondering if there was a simpler way to iterate through multiple ranges of numbers? I want to have it so I can give an argument of 4 in my function and it iterates through 4 different numbers.

I know that:

for i, j in range(10):
    print(i, j)

will iterate through i and j at the same time.

Any help would be greatly appreciated!

CodePudding user response:

You can use itertools.product to do this, it will effectively write the nested loops for you, but it's not more efficient as far as I know, it's mostly just more convenient:

from itertools import product
for i, j, k in product(range(10), range(10), range(10)):
    print(i, j, k)

EDIT: As @interjay pointed out, the repeat= argument might also be useful to you. I assumed you might not always use the same iterator for i, j, and k, but your example can be simplified further like this:

for i, j, k in product(range(10), repeat=3):
    print(i, j, k)

The itertools module has lots of convenient ways to manipulate and combine iterators.

CodePudding user response:

Is this what you want?

def loop_fun(loop_number, *args):
    if loop_number:
        for i in range(10):
            loop_fun(loop_number-1, i, *args)
            if loop_number == 1:
                print(*args, i)


loop_fun(4)

CodePudding user response:

Is this what you want?

def loop_fun(loop_number, *args):
if loop_number:
    for i in range(10):
        loop_fun(loop_number-1, i, *args)
        if loop_number == 1:
            print(*args, i)
  • Related