Flatten..with less recursion

Nick Perkins nperkins7 at home.com
Fri May 25 14:13:53 EDT 2001


>
> def flatten(L):
>     if type(L) != type([]): return [L]
>     if L == []: return L
>     return flatten(L[0]) + flatten(L[1:])


...hmm
this might make a good Scheme program,
but I would consider this excessive and
unnecessary recursion in any language that
does not do proper tail recursion.
Python performance on any long list would
probably be very bad.
(hmm...Stackless?...i wonder...)

..what about:

def flatten(L):
    if type(L) != type([]): return [L]
    if L == []: return L
    return reduce(lambda L1,L2:L1+L2,map(flatten,L))



...maybe someone knows how to avoid the lambda,
but I think this should be much faster.











More information about the Python-list mailing list