tricky nested list unpacking problem

Arnaud Delobelle arnodel at
Tue Dec 16 11:15:08 CET 2008

bearophileHUGS at writes:

> I was waiting to answer because so far I have found a bad-looking
> solution only. Seeing there's only your solution, I show mine too. It
> seems similar to your one.

I think that the solution below is a bit clearer, although I think it is
more resource intensive than my first one.  I've switched to a generator
function to make it more easily comparable.  It's true that it's a
problem that seems designed for Scheme!

l1 = [1,2,3,[5,6]]
l2 = [1,2,3,[5,6],[7,8,9]]
l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]

def flatten(x):
    if isinstance(x, list):
        for y in x:
            for z in flatten(y):
                yield z
        yield x

def unpack(lst, acc=[]):
    i = len(acc)
    if i == len(lst):
        yield '-'.join(map(str, acc))
        for x in flatten(lst[i]):
            for res in unpack(lst, acc + [x]):
                yield res


More information about the Python-list mailing list