Search code examples
pythonlistlambdalist-comprehensionpython-itertools

Using itertools to create all combinations up to a value


I have this code:

return [reduce(lambda x,y: str(x)+str(y), perm) 
        for perm in itertools.combinations(alphabet, n)]

My problem is I want it to be for all values up to n. It's for homework and I'm having trouble making this a single line Pythonic statement. How would I continue in this manner so I could add a statement like:

 return [reduce(lambda x,y: str(x)+str(y), perm) 
         for perm in itertools.combinations(alphabet, n) for n in range(1,n+1)] 

except one that actually works?


Solution

  • Something like this?

    >>> from itertools import combinations, chain
    >>> limit = 10
    >>> c = chain(*(combinations(alphabet, x) for x in range(1, limit+1)))
    >>> list(c)
    

    I won't display the output, it's too long.

    Edit: based on your comments above, it seems like you want the output in the form of strings, so

    [''.join(s) for s in chain(*(combinations(alphabet, x) for x in range(1, limit+1)))]