Search code examples
pythonalgorithmcombinationspermutation

find all n-long permutations (with repeats) of m-long list, n>m


Say I have some list [0,1,2]. I then want return all n-long "permutations" of this list. For example, if n=5, I should have 3^5 choices enumerated:

[0,0,0,0,0]
[0,0,0,0,1]
[0,0,0,0,2]
[0,0,0,1,0]
...
[2,2,2,2,2]

I've been browsing for a post like this on stack overflow for a while and have tried many functions in the itertools library, including combinations, combinations_with_repeats, permutations, etc, but none of these will give me the output I desire. It's not hard to code myself, but I feel like a 5-fold nested loop will look very messy in my code, and I'd rather use an implementation in another library if it exists. I think I'm just searching in the wrong place. Thanks


Solution

  • Python's itertools.product will do exactly what you need.

    import sys
    from itertools import product
    
    DIGITS = (0, 1, 2)
    N = int(sys.argv[1])
    
    for tup in product(DIGITS, repeat = N):
        print(tup)