[Tutor] Issues with initializing lists

Leona Euler gyromagnetic@excite.com
Fri, 10 Aug 2001 06:57:24 -0700 (PDT)


Hi,
I am a bit confused about the usage of lists in Python. For an application I
am writing, I would like to create a list of lists with some default values,
and then fill in certain items in the list later. 

As an example:
>>> l1=[[None]*3]*4
>>> l1
[[None, None, None], [None, None, None], [None, None, None], [None, None,
None]]

Now, suppose I want to fill in the second item in the second sublist. I try
>>> l1[1][1]='hello'

Then 'l1' looks like

>>> l1
[[None, 'hello', None], [None, 'hello', None], [None, 'hello', None], [None,
'hello', None]]

Note how 'hello' has propagated to each sublist.

Why is this?


I could do

l1=[]
>>> for i in range(4):
... 	l1.append([])
... 	for j in range(3):
... 		l1[i].append(None)
... 
l1[1][1]='hello'
>>> l1
[[None, None, None], [None, 'hello', None], [None, None, None], [None, None,
None]]

This looks fine. But this approach really seems excessive. 

My real question is how do I conveniently initialize such a list so that I
can later fill in the sublists?

Thanks.

-Brad





_______________________________________________________
Send a cool gift with your E-Card
http://www.bluemountain.com/giftcenter/