Recursive list comprehension

Adam DePrince adam at
Wed Dec 8 20:14:22 CET 2004

On Mon, 2004-12-06 at 10:01, Timothy Babytch wrote:
> Serhiy Storchaka wrote:
>  >>>sum([['N', 'F'], ['E'], ['D']], [])
> ['N', 'F', 'E', 'D']
> -- 
> Timothy Babytch, PHP-dev Teamleader

Sum certainly takes the cake for hackish elegance, and would be my
choice if I was absolutely certain that my data structure was exactly a 
list of lists.   A more general solution with applicability to arbitrary
levels of nesting is below.

a = [['N','F'],['E'],['D']]
b = [[['A','B',['C','D']],'N','F'],'E', ['F'] ]
c = iter([[iter(['A','B',('C','D')]),'N','F'],'E', iter(['F']) ])

def flatten( i ):
        i = i.__iter__()
        while 1:
            j = flatten( )
                while 1:
            except StopIteration:
    except AttributeError:
        yield i

if __name__ == "__main__":
    print list( flatten( a ) )
    print list( flatten( b ) )
    print list( flatten( c ) )

Which when run gives you ... 

['N', 'F', 'E', 'D']
['A', 'B', 'C', 'D', 'N', 'F', 'E', 'F']
['A', 'B', 'C', 'D', 'N', 'F', 'E', 'F']

Adam DePrince

More information about the Python-list mailing list