Search code examples
pythoncombinationspermutationpython-itertools

Python permutations with repetitions


If I use "itertools.permutations", I don't get all possible combinations. (i.e. "abb" or "cbc")

import itertools
charList = ["a", "b", "c"]

per = itertools.permutations(charList, 3)

for val in per:
    print(val)

I'm searching for something like "itertools.product", but it works only for numbers.


Solution

  • import itertools
    x = ['a', 'b', 'c']
    print([''.join(p) for p in itertools.product(x, repeat=3)])
    

    Will produce:

    ['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']