understanding nested lists?
Vincent Davis
vincent at vincentdavis.net
Sat Jan 24 11:29:28 EST 2009
I have a short peace of code that is not doing what I expect. when I assign
a value to a list in a list alist[2][4]=z this seems replace all the 4
elements in all the sub lists. I assume it is supposed to but this is not
what I expect. How would I assign a value to the 4th element in the 2nd
sublist. here is the code I have. All the printed values are what I would
expect except that all sublist values are replaced.
Thanks for your help
Vincent
on the first iteration I get ;
new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None,
0, 1, None], [None, 0, 1, None], [None, 0, 1, None]]
and expected this;
new_list [[None, 0, 1, None], [None, None, None, None], [None, None, None,
None], [None, None, None, None], [None, None, None, None],
[None, None, None, None]]
Code;
list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]]
new_list=[[None]*4]*6
print 'new_list',new_list
for sublist in range(6): # 6 becuase it is the # of rows lists1
print 'sublist', sublist
for x in list1[sublist]:
print list1[sublist]
print 'new_list[sublist][x]', new_list[sublist][x]
new_list[sublist][x]=list1[sublist].index(x)
print 'sublist', sublist, 'x', x
print new_list[sublist][x]
print 'new_list', new_list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090124/50a33b2e/attachment.html>
More information about the Python-list
mailing list