understanding nested lists?

Brian Allen Vanderburg II BrianVanderburg2 at aim.com
Sat Jan 24 18:42:28 CET 2009


vincent at vincentdavis.net wrote:
> 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
>
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

The problem is likely this right here:

[[None]*4]*6

This first creates an inner list that has 4 Nones, then the outer list 
contains 6 references to that same list, so (new_list[0] is new_list[1]) 
and (new_list[1] is new_list[2]).  I make this mistake a lot myself.

l=[[None]*4]*6
print id(l[0])  # -1210893364
print id(l[1])  # -1210893364

l = [list([None]*4) for x in range(6)]
print id(l[0])  # -1210893612
print id(l[1])  # -1210893580

Works better

Brian Vanderburg II



More information about the Python-list mailing list