Search code examples
pythoncombinationspython-itertools

Generating multiple combinations of strings


I have a list of n letters as strings such as:

input: ["A", "B", "C", "D"]

What I need to do is create all possible combinations of these letters with given length, for example if:

L = 2
output: ["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]

L = 3
output: ["A", "B", "C"], ["A", "B", "D"], ["A", "C", "D"], ["B", "C", "D"]

Solution

  • You can use itertools.permutations to get permutations of a specified length.

    from itertools import permutations 
    
    print(list(permutations(my_list, L)))