0

I would like to have all possible combinations of lists of a given size. Lets say for example, I have a given list K, such as K = [3, 5, 2]. With the following code I get what I desire. But how do I generalize this for any list of a given size, without just adding for loops?

assignment= []
for l in range(K[0]):
    for m in range(K[1]):
        for n in range(K[2]):
            a = [l,m,n]
            assignment.append(a)
Dan Getz
  • 8,774
  • 6
  • 30
  • 64

1 Answers1

0

The itertools library can often help with things like this. itertools.product() in particular, using * to pass it a list or iterator of ranges:

list(itertools.product(*(range(n) for n in K))

or

list(itertools.product(*map(range, K)))
Dan Getz
  • 8,774
  • 6
  • 30
  • 64