Search code examples
pythonpython-itertools

How to generate combination of fix length strings using a set of characters?


In Python, how can I generate a string with all combinations of a set of characters up to a certain length?

I know how to use itertools to generate all combinations and permutations, but I can't figure out how to generate strings of dynamic length.

For example:

a = [0,1] length = 4

Result:

[0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1101, 1110, 1111]


Solution

  • You could use itertools.product:

    li = []
    for i in itertools.product([0,1], repeat=4):
        li.append(''.join(map(str, i)))
    print (li)
    
    >>> li
    ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
    

    Possible one liner:

    [''.join(map(str, i)) for i in itertools.product([0,1], repeat=4)]