Newbie confused by 2 dimensional list

Joshua Macy amused at webamused.com
Fri Aug 4 01:42:51 EDT 2000


haaserd wrote:
> 
> Hi,
> I am trying to create a two dimensional list which will
> contain single characters:
> 
> >>> L = [["*"] * 2] * 2  # initialize a 2x2 list???
> >>> L
> [['*', '*'], ['*', '*']]
> >>> L[0][1] = 'z'
> >>> L
> [['*', 'z'], ['*', 'z']]
> >>> L[0][1]
> 'z'
> >>>
> 
> When I try to set the element L[0][1] to "z", it also sets
> L[1][1] to "z".  But I seem to be able to access L[0][1] by
> itself.  What am I doing wrong?
> 
> TIA

 l = [[]] * 2 doesn't do a copy of the contents of the inner list, it
just copies the reference to the list (the list object).  Thus you have
a list with two references to the same object, which you prove by
changing the object and demonstrating that both references display the
same contents.  You want to force a copy of the inner list before you
append it to the outer list, along the lines of


 >>> inner = ['*'] * 2
 >>> inner
 ['*', '*']
 >>> outer = []
 >>> for i in range(2):
 ...	outer.append(inner[:])
 ...
 >>> outer
 [['*', '*'], ['*', '*']]
 >>> outer[0][0] = '#'
 >>> outer
 [['#', '*'], ['*', '*']]
 

I'm not sure how to do that in one step with the * syntax, though.

  Joshua



More information about the Python-list mailing list