[Tutor] 2d list index inverting?

Hugo Arts hugo.yoshi at gmail.com
Wed May 26 03:38:58 CEST 2010


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


More information about the Tutor mailing list