[Tutor] 2d list index inverting?

Dave Angel davea at ieee.org
Wed May 26 10:46:18 CEST 2010


Hugo Arts wrote:
> On Wed, May 26, 2010 at 3:13 AM, Alex Hall <mehgcap at gmail.com> wrote:
>   
>> Hello all,
>> I have a 2d list being used for a battleship game. I have structured
>> the program so that it uses a grid class, which implements this array
>> along with a bunch of other methods and vars. For example, to get at
>> the top left square, you would say:
>> Grid.getSquareAt(0,0)
>> and inside getSquareAt is simply:
>>  def getSquareAt(self, x, y):
>>  return self.b[x][y] #b is the internal 2d list for the class
>>
>> However, I am getting very confused with indexing. I keep getting
>> errors about list index out of range and I am not sure why. I have a
>> feeling that using 2d lists is supposed to go like a matrix
>> (row,column) and not like a coordinate plane (column, row).
>>     
>
> A 2D list doesn't really exist. What you're using is just a list whose
> elements are also lists. A nested data structure. And whether those
> sub-lists should be the rows or the columns? It doesn't matter. A list
> is just a list. Sequential data elements. It doesn't care whether it
> represents a row or a column. What are 'row' and 'column' anyway? just
> words designating some arbitrary notion. Conventions. You can swap one
> for the other, and the data remains accessible. As long as you're
> consistent, there's no problem.
>
> The real problem is something else entirely. Somewhere in your code,
> you are using an index that is greater than the size of the list.
> Perhaps you're not consistent, somewhere. Mixing up your row/column
> order. Perhaps something else is amiss. No way to tell from the
> snippet.
>
> Hugo
>
>   
My question would be how are you creating these lists, and how you're 
updating them.  If you're doing a 20x20 board, are you actually creating 
20 lists, each of size 20, in instance attribute b ?  Do you do that in 
the __init__() constructor?  Or are you doing some form of "sparse 
array" where you only initialize the items that have ships in them?

As for updating, are you always doing the update by assigning to 
self.b[row][col]  ?

You could always add a try/catch to the spot that crashes, and in the 
catch clause, temporarily print out the subscripts you're actually 
seeing.  As Hugo says, you could simply have values out of range.


DaveA



More information about the Tutor mailing list