[ [ [] * y for y in range(3) ] * x for x in range(2) ]
Terry Reedy
tjreedy at udel.edu
Thu Jan 30 08:00:46 CET 2003
"David Eppstein" <eppstein at ics.uci.edu> wrote in message
news:eppstein-96744E.22015129012003 at news.service.uci.edu...
> What's wrong with [[[]]*3]*2 ?
For the inner list, [[]]*3 is the same as [[] for y in range(3)]. For
the outer list, a second 'multiplication', as you must have just
forgotten, is a common newbie mistake leading to multiple references
to the *same* inner list and surprises like the following:
>>> a=[[[]]*3]*2
>>> a[0][0]=2
>>> a
[[2, [], []], [2, [], []]]
To have independent inner lists, each must be created separately.
>>> a = [[[]]*3,[[]]*3]
>>> a[0][0]=[2]
>>> a
[[[2], [], []], [[], [], []]]
More generally:
a = [[[]]*m for x in range(n)] # n rows of m empty lists.
Terry J. Reedy
More information about the Python-list
mailing list