Newbie confused by 2 dimensional list

Alan Gauld alan.gauld at gssec.bt.co.uk
Fri Aug 4 08:51:36 EDT 2000


Joshua Macy wrote:
> > 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?
> 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[:])

Or slightly simpler:

>>> inner = ['*'] * 2
>>> outer = [inner, inner[:]]
>>> outer
[['*', '*'], ['*', '*']]
>>> outer[0][1] = 'z'
>>> outer
[['*', 'z'], ['*', '*']]
>>>


The second element takes a copy of the first by 
virtue of the slicing operation.

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

Not quite one step but saves an explicit loop...

Alan G.


-- 
=================================================
This post represents the views of the author 
and does not necessarily accurately represent 
the views of BT.



More information about the Python-list mailing list