itertools.combinations will provide you with all combinations of a certain length. We take all combinations for each possible length of the subexpression. Then we match the function you are interested in (lambda function or in this case "x".join ) for each of the generated combinations.
>>> import itertools as it >>> a = ['a','b','c'] >>> l = [map("x".join, list(it.combinations(a, l))) for l in range(1,len(a)+1)] >>> l [['a', 'b', 'c'], ['axb', 'axc', 'bxc'], ['axbxc']]
Now l is the list of lists we want to flatten:
>>> [ x for y in l for x in y] ['a', 'b', 'c', 'axb', 'axc', 'bxc', 'axbxc']
source share