[Tutor] List indexing problem

Kent Johnson kent37 at tds.net
Sat Jul 26 09:15:59 CEST 2008


On Fri, Jul 25, 2008 at 8:20 PM, Michiel Overtoom <motoom at xs4all.nl> wrote:
> Mike wrote...
>
>>Do you happen to know if there is an efficient way to initialize a  list
>>like this without explicitly writing out each element?
>
>>>> temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
>>>> print temp
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>
>>>> print [[0]*3]*3
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

This has the same aliasing problem as the original:
>>> x=[[0]*3]*3
>>> x
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> x[0][0]=1
>>> x
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

BTW this is a FAQ:
http://effbot.org/pyfaq/how-do-i-create-a-multidimensional-list.htm

Kent


More information about the Tutor mailing list