flatten a level one list

Robin Becker robin at SPAMREMOVEjessikat.fsnet.co.uk
Thu Jan 12 03:54:59 EST 2006


Paul Rubin wrote:
> Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
> 
>>>>>import operator
>>>>>a=[(1,2),(3,4),(5,6)]
>>>>>reduce(operator.add,a)
>>
>>(1, 2, 3, 4, 5, 6)
> 
> 
> (Note that the above is probably terrible if the lists are large and
> you're after speed.)
yes, and it is all in C and so could be a contender for the speed champ. 
I guess what you're saying is that it's doing

(1,2)
(1,2)+(3,4)
(1,2,3,4)+(5,6)

ie we do n or n-1 tuple additions each of which requires tuple 
allocation etc etc

A fast implementation would probably allocate the output list just once 
and then stream the values into place with a simple index.
-- 
Robin Becker



More information about the Python-list mailing list