understanding nested lists?

Vincent Davis vincent at vincentdavis.net
Sat Jan 24 21:02:25 CET 2009


Thanks for the info. I did not know that.
Thanks
Vincent Davis



On Sat, Jan 24, 2009 at 10:46 AM, Steve Holden <steve at holdenweb.com> wrote:

> Vincent Davis 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
> >
> When you create new_list you are actually filling it with six references
> to the same list. Consequently when you change one of those list
> elements they all appear to change (because they are all referencing the
> same list object).
>
> Try instead
>
> new_list = [[None]*4 for i in range(6)]
>
> and you should find your code works as expected. In this case the list
> is constructed with a new sublist as each element.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090124/f3dc6eb6/attachment.html>


More information about the Python-list mailing list