List Question

Tom Jenkins tjenkins at nospiced.ham.devis.com
Fri Jul 20 13:44:24 EDT 2001


Donovan Hide wrote:

> Given:
> 
> a=[[0]*6]*6
> a[3][3]=4
> print a

> [[0, 0, 0, 4, 0, 0], [0, 0, 0, 4, 0, 0], [0, 0, 0, 4, 0, 0], [0, 0, 0, 4, 0,
> 0], [0, 0, 0, 4, 0, 0], [0, 0, 0, 4, 0, 0]]
> 

Your syntax for changing the cell is correct.  However, you may be thinking that you're putting in separate list objects in the outside list but you're not.  That's why all of the lists are getting the change.

> 
> What syntax should I use to get this result:
> 
> [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 4, 0,
> 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
> 


b = [0]*6
a = []
for i in range(0,6):
     # make a copy of b and put into a
     a.append(b[:])


or alternatively in 2+
a = [[0]*6 for x in range(0,6)]

a[3][3] = 4

(btw that was my very first list comprehension that i've ever thought of 
and written.  I was quite amazed when in worked.)

<python-still-amazes-me-ly> yours,

Tom





More information about the Python-list mailing list