Creating a List of Empty Lists
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Dec 4 10:00:05 EST 2003
michael at foord.net (Fuzzyman) wrote in
news:8089854e.0312040649.4a7f1715 at posting.google.com:
> I eventually discovered that (as a silly example) :
> a = [[]]*10
> b=-1
> while b < 10:
> b += 1
> a[b] = b
> print a
>
> Produced :
> [ [9], [9], [9]......
>
> Which isn't at all what I intended...............
> What is the correct, quick way of doing this (without using a loop and
> appending...) ?
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) ]
--
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