Enumerate possible result of N choices K times

I'm trying to find an efficient way to enumerate all the possible outcomes of choosing from N options (with replacement) K times.

For example:

func(N=2, K=3) => [[0,0,0],[1,0,0],[0,1,0],[0,0,1],[1,1,0],[1,0,1],[1,1,1],[0,1,1]]

func(N=3, K=2) => [[0,0],[1,0],[2,0],[0,1],[0,2],[1,2],[2,2],[2,1],[1,2]]

What is a general way to do this in Python?


Here is the example that does what you want, except that elements were sorted

import itertools

def func(N, K):
    return list(itertools.product(range(N), repeat=K))


print(func(N=2, K=3))
# => [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

print(func(N=3, K=2))
# => [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]