idiom for initial list of lists

Tim Hochberg tim.hochberg at ieee.org
Fri Sep 8 15:55:14 EDT 2000


Dan Schmidt <dfan at harmonixmusic.com> writes:

> Robin Becker <robin at jessikat.fsnet.co.uk> writes:
> 
> | 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([])


Here's another way, although it's only practical if your already using NumPy.

S = Numeric.zeros([5,0]).tolist()

-tim



More information about the Python-list mailing list