flatten a list of list

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Aug 16 07:08:09 EDT 2009


On Sun, 16 Aug 2009 12:03:53 +0200, Michael Fötsch wrote:

> Terry wrote:
>> Is there a simple way (the pythonic way) to flatten a list of list?
> 
> This is probably the shortest it can get:
> 
> sum(list_of_lists, [])


That's also O(N**2).


>>> from timeit import Timer
>>> setup = "L = [ ([None]*5000) for x in xrange(%d) ]"
>>> Timer("sum(L, [])", setup % 4).repeat(number=1000)
[0.6070549488067627, 0.54354715347290039, 0.54686999320983887]
>>> Timer("sum(L, [])", setup % 8).repeat(number=1000)
[2.1285719871520996, 3.6722278594970703, 4.0785009860992432]
>>> Timer("sum(L, [])", setup % 16).repeat(number=1000)
[18.370341062545776, 20.40509295463562, 21.871708869934082]



-- 
Steven



More information about the Python-list mailing list