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

George Sakkis gsakkis at rutgers.edu
Mon Jul 4 17:23:29 CEST 2005


"Tom Anderson" <twic at urchin.earth.li> wrote:

> I'll just chip in and say i'd quite like a flatten(), too; at the moment,
> i have one like this:
>
> def flatten(ll):
>   return reduce(lambda a, l: a.extend(l), ll, [])

This doesn't work; a.extend() returns None, not the extended list a:

>>> seq = [[1,2],[3],[],[4,[5,6]]]
>>> flatten(seq)
AttributeError: 'NoneType' object has no attribute 'extend'

This works for 1-level flattening:

def flatten(ll):
    return reduce(lambda a, l: a.extend(l) or a, ll, [])

>>> flatten(seq)
[1, 2, 3, 4, [5, 6]]

And finally for recursive flattening:

def flatten(seq):
    return reduce(_accum, seq, [])

def _accum(seq, x):
    if isinstance(x,list):
        seq.extend(flatten(x))
    else:
        seq.append(x)
    return seq

>>> flatten(seq)
[1, 2, 3, 4, 5, 6]


George




More information about the Python-list mailing list