map/filter/reduce/lambda opinions and background unscientific mini-survey

George Sakkis gsakkis at rutgers.edu
Tue Jul 5 21:59:28 CEST 2005


"Devan L" wrote:

> def flatten(iterable):
>     if not hasattr(iterable, '__iter__'):
>         return [iterable]
>     return sum([flatten(element) for element in iterable],[])
> Recursion makes things so much shorter.

The last line can faster and more compact by:

from itertools import imap

def flatten(iterable):
    if not hasattr(iterable, '__iter__'):
        return [iterable]
    return sum(imap(flatten,iterable),[])

George




More information about the Python-list mailing list