idiom for initial list of lists

Edward C. Jones edcjones at erols.com
Fri Sep 8 19:19:00 EDT 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]]
>
> so I'm forced to use the rather pedantic
> S=[]
> for i in range(n): S[i].append([])
> --
> Robin Becker

Most languages have dark corners where it is better to neither look nor
go. The initialization of nested lists is a dark corner of Python which
is unfortunately high visible and heavily travelled. I have written
something about this at:
http://members.tripod.com/~edcjones/pycode.html .




More information about the Python-list mailing list