Creating a List of Empty Lists

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Dec 8 04:47:20 EST 2003


Robin Becker <robin at jessikat.fsnet.co.uk> wrote in
news:SWfFiLAYAi0$EwHZ at jessikat.fsnet.co.uk: 

> In article <Xns9447973F01BFduncanrcpcouk at 127.0.0.1>, Duncan Booth
><duncan at NOSPAMrcp.co.uk> writes
> ......
>>
>>The recommended way these days is usually:
>>
>>    a = [ [] for i in range(10) ]
>>
>>That still has a loop and works by appending empty lists, but at least
>>its just a single expression. Also you can incorporate the next stage
>>of your initialisation quite easily:
>>
>>    a = [ [b] for b in range(10) ]
>>
> I seem to remember the fastest way to do this was map(list,n*[[]])
> from a couple of earlier threads, but is that true in 2.3?

I think I would prefer to maintain code with the list comprehension rather 
than the map which, to my eyes, isn't immediately obvious. However, it 
would appear that the list comprehension is much faster in any case, so in 
this case I believe the clearest solution is also the fastest. 

C:\>d:\python23\lib\timeit.py "[ [] for i in range(10) ]"
10000 loops, best of 3: 28.6 usec per loop

C:\>d:\python23\lib\timeit.py "map(list,10*[[]])"
10000 loops, best of 3: 102 usec per loop

C:\>d:\python23\lib\timeit.py -s ll=list -s mm=map "mm(ll,10*[[]])"
10000 loops, best of 3: 91.9 usec per loop

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list