Question about nested lists!

Steven D. Majewski sdm7g at Virginia.EDU
Thu Aug 2 23:31:02 EDT 2001


On 2 Aug 2001, rainlet wrote:

> I use a nested list to make a 2-d array. The code follows:
> 
>     floor_member = [ 0 ]
>     for x in range ( 9 ) :
>         floor_member.append ( 0 )
>     floor = [ floor_member ]
>     for y in range ( 9 ) :
>         floor.append ( floor_member )
>     floor [ 5 ] [ 5 ] = 1
>     for n in range ( 10 ) :
>         print floor [ n ]
> #code end
> 
> I only assign floor [ 5 ] [ 5 ] = 1, but the result is :
> 
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
> 
> 
> Is this a bug? Please help me debug. I can't see anything wrong!

>     for y in range ( 9 ) :
>         floor.append ( floor_member )

You are appending the SAME OBJECT 9 times!!!

( after first initializing the list with it )

try something like:

	floor = []
	for i in range(10):
		floor.append( [0]*10 )


Or, as a list-comprehension:

	[[ 0 for x in range(10) ] for y in range(10) ]



Or,  at least change:

>     for y in range ( 9 ) :
>         floor.append ( floor_member )


to:

>     for y in range ( 9 ) :
>         floor.append ( floor_member[:] )


the [:] slice indexing makes a copy of the list. 


This is in the FAQ, and repeated dozens of times in the list archives. 

-- Steve Majewski






More information about the Python-list mailing list