Newbie confused by 2 dimensional list

Duncan Booth duncan at rcp.co.uk
Mon Aug 7 09:55:35 EDT 2000


amused at webamused.com (Joshua Macy) wrote in 
<398A4A02.3AD9BF85 at webamused.com>:

> >>> 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.
>

If you are desparate to avoid the for loop you can always do:

>>> import copy
>>> L = map(copy.copy, [["*"]*2]*2)
>>> L[0][0] = '#'
>>> L
[['#', '*'], ['*', '*']]

which gives the desired effect, arguably at the expense of program clarity.



More information about the Python-list mailing list