4

While implementing Matrix multiplication for university, I eventually got a 3 times nested for-loop, using only ranges. I personally do not like nesting and asked myself if there is something in Python that could "simplify" the syntax of this special case.

I looked that up in the internet but unfortunately i was not able to find anything.

The code I got looked somewhat like this:

for i in range(a):
    for j in range(b):
        for k in range(c):
            # some stuff

With Python being able to return multiple values I thought there should be some iterator returning N indices of N nested range-using for-loops, like:

# this should do the exact same thing like the above example
for i, j, k in nrange((a), (b), (c)):
    # some stuff

Every argument of nrange is a tuple of arguments which then gets passed with the * operator to range. So nrange((a1, a2, a3), (b1, b2, b3)) should also be possible. My question, does this exist, and if not, why?

Thank you in advance. :)

bchmnnjcb
  • 76
  • 4
  • 1
    You can use the `itertools` library, and the `itertools.product()` function. However, matrix computation are far more efficient in numpy with the build-in functions. – Mathieu Nov 06 '19 at 10:47
  • You can checkout these answers for single line nested for loops https://stackoverflow.com/questions/17006641/single-line-nested-for-loops – Akash Basudevan Nov 06 '19 at 10:49

1 Answers1

5

Yes there is itertools.product

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

Output:

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
2 2 0
2 2 1
2 2 2
ExplodingGayFish
  • 2,807
  • 1
  • 5
  • 14