[Tutor] Nested lists help

Dave Angel davea at davea.name
Sat Oct 19 06:42:58 CEST 2013


On 18/10/2013 20:13, Corinne Landers wrote:


> --></style></head>
> <body class='hmmessage'><div dir='ltr'>Hi, <div><br></div><div>I'm trying to create a 3D grid, so I'm using a list of list of lists. </div><div>However, if I try to make a change to one value, eg</div><div>grid[0][1][2] = 3, </div><div>It doesn't just change list[0], it change the 2nd element in the 1st list of every list? </div><div>I think it's because I've copied lists to get the grid, but could you help me fix this? </div><div><br></div><div>This is my code, that takes an x,y,z value from user. </div><div><br></div><div><div>self.grid_x = x</div><div>self.grid_y = y</div><div>self.grid_z = z</div><div><br></div><div>self.grid = []</div><div>self.grid2D = []</div><div><br></div><div>for i in range(self.grid_y):</div><div>            row = [0]*x</div><div>            self.grid2D.append(row)</div><div><br></div><div>for k in range(z):</div><div>            self.grid.append(self.grid2D) #Creates list of x by y grids</div></div><div><br></div><div>Thank you so much</div><div>Corrine</div> 		 	   		  </div></body>
> </html>
>
>

Please don't post using html mail.  Use text email for a text newsgroup.
 Not only does it waste space (since the message essentially has two
copies of what you type, the html part being much larger than what you
typed), but it also can frequently lose all the indentation (as happened
to this message
in your email program).  Indentation matters in Python.  Your lines are
also run together in places, like the first line of your code, which
looks like this:
    self.grid_x = xself.grid_y = yself.grid_z = z



The problem you have, as you have guessed, is that you're making
references to the same list multiple times.  So when that list is
changed, it changes all references.  You need to have every item in your
nested list be unique.

The simplest change is to use
   myotherlist = mylist[:]

to make a copy of each element of the list.  That's not necessary at the
innermost level, since integers are immutable.

I'm not sure what to make of your code, since you say you want a 3d
grid, but you're only making 2d.  But to make a 3d list, you might use
something like  (untested):

my_3d_list = []
for i in range(x):
    temp1 = []
    for j in range(y):
        temp2 = []
        for k in range(z):
              temp2.append(0)
        temp1.append(temp2)
    my_3d_list.append(temp1)

The innermost loop could be replaced by
       temp2 = [0]*z

but I like the symmetry of the way I wrote it.



-- 
DaveA




More information about the Tutor mailing list