map/filter/reduce/lambda opinions and background unscientificmini-survey

Terry Reedy tjreedy at udel.edu
Thu Jul 7 16:36:29 EDT 2005


"Pawe³ Sakowski" <pawel at sakowski.pl> wrote in message 
news:dajghf$dit$1 at inews.gazeta.pl...
Tom Anderson wrote:
> def flatten(ll):
>  return reduce(lambda a, l: a.extend(l), ll, [])
>
> How would one do that as a list comp, by the way? I'm really not very 
> good
> with them yet.

Not really a list-comprehension based solution, but I think what you want 
is

>>> ll=[[1,2],[3,4,5],[6]]
>>> sum(ll,[])
[1, 2, 3, 4, 5, 6]

Unless sum knows to typecheck input items and special-case lists and use 
list.extend rather than list+list, this turns an O(n) operation into an 
O(n**2) operation.  Sum is meant for numbers.

Terry J. Reedy






More information about the Python-list mailing list