idiom for initial list of lists

Bryn Keller brk at jenkon.com
Fri Sep 8 13:14:18 EDT 2000


Oleg Broytmann wrote:

> 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.

Well. There are alternatives, even if they amount to the same thing:

>>> s = map(lambda x:[], xrange(5))
>>> s
[[], [], [], [], []]
>>> s[0].append(1)
>>> s
[[1], [], [], [], []]
>>>

Bryn

>
>
> Oleg.
> ----
>      Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
>            Programmers don't die, they just GOSUB without RETURN.




More information about the Python-list mailing list