understanding nested lists?

Steve Holden steve at holdenweb.com
Sat Jan 24 12:46:14 EST 2009


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/




More information about the Python-list mailing list