Search code examples
pythoncombinationscombinatoricspython-itertools

All possible combinations of letters from a list, from 1 to 20 - python


Currently trying to get this to create all possible combinations of these 20 letters in a list, (without repeats)

letters = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T']

combinations = [''.join(i) for i in itertools.combinations(letters,r=20)]

Output I'm looking for is a list like:

combinations = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T',GG,GA,GL,GM... ...GALMFWKQESPVICYHRNDT]

Solution

  • You could use a nested loop in the list comprehension to iterate through all possible lengths:

    letters = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T']
    
    combinations = [''.join(i) for j in range(1,len(letters) + 1) for i in itertools.combinations(letters,r=j)]