[ [ [] * y for y in range(3) ] * x for x in range(2) ]
Andrew Bennetts
andrew-pythonlist at puzzling.org
Thu Jan 30 00:09:42 EST 2003
On Wed, Jan 29, 2003 at 08:34:05PM -0800, Marcel wrote:
> Hi,
>
> I'm trying to allocate nested lists up-front using the subject line,
> instead of generating :
> [ [ [], [], [] ], [ [], [], [] ] ]
> I end up with :
> [ [], [ [], [], [] ] ]
>
> I guess I screwed up something, but I'm failing to understand what...
>
> Any idea ?
Try:
[[[] for y in range(3)] for x in range(2)]
You don't want to multiply the lists, which copies the contents -- in fact,
multiplying an empty list by anything will always give you an empty list.
Why are you pre-allocating the lists, anyway? The speed difference should
be negligible to just doing someList.append(..) as appropriate.
-Andrew.
More information about the Python-list
mailing list