Initializing a list of lists

T

tkpmep

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
[[0], [0], [0]]

If I now try extending the lists indepently, I cannot, as they all
point to the same list object
[[0, 1], [0, 1], [0, 1]]

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

Thanks in advance

Thomas Philips
 
T

Tim Chase

The above construct works if I have only few items, but if I have many,
I'd prefer to write

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

If I now try extending the lists indepently, I cannot, as they all
point to the same list object

[[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
 
R

Ron Adam

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
[[0], [0], [0]]

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top