i'm lost in list manipulation

Paul Rubin http
Thu Mar 4 04:39:00 EST 2004


"GrelEns" <grelens at NOSPAMyahoo.NOTNEEDEDfr> writes:
> i'm not happy with this code, must be an other shorter alternative, have you
> any siggestions on how to build these sets  [[1], [2], [3], [1, 2], [1, 3],
> [2, 3], [1, 2, 3]] from [1,2,3] ?

def subsets(lst):
    def subgen(lst):
        if not lst:
            yield lst
            return
        for s in subsets(lst[1:]):
            yield s
            yield [lst[0]] + s
    return list(subgen([1,2,3]))[1:]  # discard empty subset

print subsets([1,2,3])



More information about the Python-list mailing list