tricky nested list unpacking problem

Scott David Daniels Scott.Daniels at Acm.Org
Mon Dec 15 23:28:43 CET 2008

Kirk Strauser wrote:
> At 2008-12-15T19:06:16Z, Reckoner <reckoner at> writes:
>> The problem is that I don't know ahead of time how many lists there are or
>> how deep they go. In other words, you could have:
> Recursion is your friend.
> Write a function to unpack one "sublist" and call itself again with the new
> list.  For instance, something like:
> def unpack(pattern):
>     # Find the first subpattern to replace
>     # [...]
>     results = []
>     for number in subpattern:
>         results.append(pattern.replace(subpattern, number))
>     return results
> Calling unpack([1,2,3,[5,6],[7,8,9]]) would look cause it to call
> unpack([1,2,3,5,[7,8,9]]) and unpack([1,2,3,6,[7,8,9]]), compile the
> results, and return them.

Along these lines generators are the bees knees.

def expands(source):
     '''Nested lists to list of flat lists'''
     for n, val in enumerate(source):
         if isinstance(val, list):
             assert val, 'empty list @%s in %s undefined.' % (
                            n, len(source))
             head = source[: n]
             tail = source[n + 1 :]
             for element in val:
                 for row in expands(head + [element] + tail):
                     yield row
         if source: # Just to make expands([]) return an empty list)
             yield source

def answer(source):
'''Do the requested printing'''
     for row in expands(source):
         print '-'.join(str(x) for x in source)

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list