470,636 Members | 1,462 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,636 developers. It's quick & easy.

Initializing a list of lists

I want to create a list of lists, each of which is identical, but which
can be modified independently i.e:
x = [ [0], [0], [0] ]
x[0].append(1)
x [[0, 1], [0], [0]]

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?

Thanks in advance

Thomas Philips

Mar 19 '06 #1
3 1824
ZeD
Ciao, tk****@hotmail.com! Che stavi dicendo?
Is there a simple way to create a list of independent lists?


N=3
x=[[0] for e in range(N)]

--
Up da 1 giorno, 3 ore, 43 minuti e 10 secondi

Mar 19 '06 #2
> 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

Mar 19 '06 #3
tk****@hotmail.com wrote:
I want to create a list of lists, each of which is identical, but which
can be modified independently i.e:
x = [ [0], [0], [0] ]
x[0].append(1)
x [[0, 1], [0], [0]]

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?

Try this...

x, y, value = 3, 3, 0
L = [[value]*x for i in xrange(y)]
Cheers,
Ron




Mar 19 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Glen Able | last post: by
14 posts views Thread by KraftDiner | last post: by
16 posts views Thread by Michael M. | last post: by
19 posts views Thread by Dongsheng Ruan | last post: by
36 posts views Thread by pereges | last post: by
1 post views Thread by Korara | last post: by
???
1 post views Thread by Stoney L | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.