I'm looking for a method to have a variable number of nested for loops instead of the following code. For example if the variable n represents the number of nested for loops and n = 3, my code would be:
p = []
for i in range(26):
for j in range(26):
for k in range(26):
p.append([i,j,k])
Instead, if n = 2 my code would be:
p = []
for i in range(26):
for j in range(26):
p.append([i,j])
I understand this can be done using recursion but I'm a bit confused as to how I'd go about doing this.
Something like this should work:
This solution uses the optimized functions of
itertools
, so it should be quite fast.Mind that
itertools.product
returns an iterator, so one needs to transform it to get an array.It's important for one to develop the skills to reason about these problems. In this case, Python includes
itertools.product
but what happens the next time you need to write a behaviour specific to your program? Will there be another magical built-in function? Maybe someone else will have published a 3rd party library to solve your problem?Below, we design
product
as a simple recursive function that accepts 1 or more lists.Assuming you want a more conventional iteration ordering, you can accomplish do so by using an auxiliary
loop
helper