Question about nested lists!

Alex Martelli aleaxit at yahoo.com
Fri Aug 3 02:39:25 EDT 2001


"rainlet" <orrego at mail2000.com.tw> wrote in message
news:f37349a7.0108021859.4f620ec2 at posting.google.com...
> 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 )

This buils a peculiar structure indeed, 10 items all
referring to the same list object.  Simpler:

floor = [ [0]*10 for x in range(10) ]

and now the anomaly you've observed (and many
others) disappear (this is also faster & more
concise, of course).

If you insist in doing it your way, at least you have
to modify your code so a COPY of floor_member is
used each time rather than the object itself, using
    floor.append(floor_member[:])
as the last statement.


Alex






More information about the Python-list mailing list