470,636 Members | 1,462 Online

# 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 = [ , ,  ]
x.append(1)
x [[0, 1], , ]

The above construct works if I have only few items, but if I have many,
I'd prefer to write N =3
x =N*[]
x [, , ]

If I now try extending the lists indepently, I cannot, as they all
point to the same list object x.append(1)
x

[[0, 1], [0, 1], [0, 1]]

Is there a simple way to create a list of independent lists?

Thomas Philips

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

N=3
x=[ 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*[]
x
[, , ]

If I now try extending the lists indepently, I cannot, as they all
point to the same list object
x.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 = [ for _ in range(N)]
x.append(1)
x

[[0, 1], , , , , , , , , ]

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 = [ , ,  ]
x.append(1)
x [[0, 1], , ]

The above construct works if I have only few items, but if I have many,
I'd prefer to write N =3
x =N*[]
x [, , ]

If I now try extending the lists indepently, I cannot, as they all
point to the same list object x.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.