Initializing a list of lists

Tim Chase python.list at tim.thechases.com
Sun Mar 19 16:39:36 CET 2006


> The above construct works if I have only few items, but if I have many,
> I'd prefer to write
> 
>>>>N =3
>>>>x =N*[[0]]
>>>>x
> 
> [[0], [0], [0]]
> 
> If I now try extending the lists indepently, I cannot, as they all
> point to the same list object
> 
>>>>x[0].append(1)
>>>>x
> 
> [[0, 1], [0, 1], [0, 1]]
> 
> Is there a simple way to create a list of independent lists?

My first thought would be

 >>> N = 10
 >>> x = [[0] for _ in range(N)]
 >>> x[0].append(1)
 >>> x
[[0, 1], [0], [0], [0], [0], [0], [0], [0], [0], [0]]

HTH,

-tkc






More information about the Python-list mailing list