idiom for initial list of lists

Robin Becker robin at jessikat.fsnet.co.uk
Sat Sep 9 05:46:33 EDT 2000


In article <Pine.LNX.4.21.0009081645290.1107-100000 at fep132.fep.ru>, Oleg
Broytmann <phd at phd.russ.ru> writes
>On Fri, 8 Sep 2000, Robin Becker wrote:
>> What's the correct way to initialise a list of lists I find that the
>> natural [[]]*n doesn't work eg
>> >>> S=[[]]*5
>> >>> S
>> [[], [], [], [], []]
>> >>> S[0].append(1)
>> >>> S
>> [[1], [1], [1], [1], [1]]
>
>   Well-known feature :)
>
>> so I'm forced to use the rather pedantic
>> S=[]
>> for i in range(n): S[i].append([])
>
>   That's the only and one correct way.
>
...
after a bit of searching and brain wracking I tried 
        
S=map(copy,n*[[]])

but even this is slower than the for loop. The same
is true of 

S=map(lambda x: x[:],n*[[]])

The only thing I could come up with was

S=map(lambda x:[], range(n))

which is about the same speed as the looping method.

It seems a bit strange that copy is not a C extension or rather that
copy.copy isn't a builtin.
-- 
Robin Becker



More information about the Python-list mailing list