Home > Mobile >  Replace nested for loops over a set of integers with list of all possible pairings in python
Replace nested for loops over a set of integers with list of all possible pairings in python

Time:03-29

I have the following:

for i1 in range(6):
    for i2 in range(6):
        for i3 in range(6):
            for i4 in range(6):
                # do stuff

I want to replace it with:

for i in possibilities:
    # do stuff

where

possibilities = [[0,0,0,0],[0,0,0,1],...,[5,5,5,5]]

How can I construct this list for any number of nested loops? Is itertools the way to go?

CodePudding user response:

Yes, you can use itertools.product to achieve that

import itertools
r = range(6)
for i in itertools.product(r,r,r,r):
    print(i)

This will print

(0, 0, 0, 0)
(0, 0, 0, 1)
(0, 0, 0, 2)
(0, 0, 0, 3)
(0, 0, 0, 4)
(0, 0, 0, 5)
(0, 0, 1, 0)
(0, 0, 1, 1)
...
(5, 5, 5, 4)
(5, 5, 5, 5)
  • Related