Marco Marco - 2 months ago 13
Python Question

Python: concatenating a given number of loops

I have this part of a code:

N = 4
coa = []
for a in range(N):
for b in range(N):
for c in range(N):
for d in range (N):
coa.append(a,b,c,d)


Basically, I need to concatenate as many for-loop as the number
N
. Therefore, if
N
had been equal to
6
, I would have had to add other two for-loops with letters
e
and
f
and to add the same letters inside
coa.append()
. Is there a possibility to do that automatically, meaning that by varying the integer value of N, all that is done without typing it?

Answer

You can use itertools.product and repeat():

Here is an example:

In [3]: from itertools import product, repeat

In [5]: 

In [5]: list(product(*repeat(range(3), 3)))
Out[5]: 
[(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)]