0

Is there a built-in function to help hide independent nested for loops?

Since they do not depend on one another to generate the next item a function could take in iterables as arguments and yield the appropriate number of items.

From:

for i in range(x):
    for j in range(y):
        for z in range(z):
            do_something()

to:

for i, j, k in iterate_over(range(x), range(y), range(z)):
    do_something()
izxle
  • 386
  • 1
  • 3
  • 19
  • 1
    `itertools.product` – Julien Mar 20 '18 at 00:52
  • 1
    Sounds pointless. – StackSlave Mar 20 '18 at 00:55
  • as @PHPglue points, if `do_something` doesn't depend on `i,j,k` you may as well use a single loop: `for _ in range(x*y*z):` – Julien Mar 20 '18 at 00:57
  • You can write this yourself pretty easily. But `itertools.product` as suggested by @Julien has the advantage that (1) it's a well-known function that any experienced Python dev will understand in your code, and (2) it might be faster than what you'd build yourself. – abarnert Mar 20 '18 at 00:59
  • @PHPglue Normally you don't use this on three ranges, you use it on some useful pair of sequences where you want the cartesian product (without building the whole list in memory). In other words, it's exactly as useless as a nested loop statement is… – abarnert Mar 20 '18 at 01:00
  • `import itertools` `x = 15; y = 10; z = 5` `for i, j, k in itertools.product(range(x), range(y), range(z)): print i, j, k` – Michael Swartz Mar 20 '18 at 01:05

0 Answers0