0

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 insidecoa.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?

Farhan.K
  • 3,425
  • 2
  • 15
  • 26
Marco
  • 5
  • 3

1 Answers1

1

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)]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    Thanks a lot. Sorry if my question was a diplicate of a precedent one. Anyway, I haven't been able to understand the previous answer, whereas this one is perfect!!! – Marco Sep 15 '16 at 13:39