# [Tutor] indexing lists

Michael P. Reilly arcege@shore.net
Mon, 5 Jun 2000 12:34:30 -0400 (EDT)

```>
> Hi everyone,
>
> I'm wondering how, if even possible, you'd find the index of a given number
> in the following list of lists:
>
> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>
> I've been playing around with my little tic tac toe program, and I can't
> decide whether to use this list of lists structure for the matrix or a
> simpler [1, 2, 3, 4, 5, 6, 7, 8, 9] structure.
>
> I think programming the strategy might be easier with the more 2-dimensional
> list of lists. But finding which moves are possible involves determining
> which places in the list are occupied by integers, not "X" or "O". I need to
> do l.index(spam) for that. Unfortunately, I can't do l.index(5). I can do
> l.index([1, 2, 3]), however. Is it possible to get at that 2nd layer of
> lists through an index statement?

import types
from UserList import UserList

class Board(UserList):
dimension = 3
def __init__(self, dimension=None):
UserList.__init__(self)
if dimension is not None:
self.dimension = int(dimension)
# flesh out the board by putting in None's
for i in range(self.dimension ** 2):
self.append(None)
def __getitem__(self, index):
if isinstance(index, types.TupleType):
(row, column) = index
index = row * self.dimension + column
return UserList.__getitem__(self, index)
def __setitem__(self, index, value):
if isinstance(index, types.TupleType):
(row, column) = index
index = row * self.dimension + column
UserList.__setitem__(self, index, value)
def index(self, value):
position = UserList.index(self, value)
row, column = divmod(position, self.dimension)
return (row, column)

b = Board(4)
b[1,0] = 3
print b.index(3)
(1, 0)

Use the existing tools when you can, and think about what functions you
might need.  For example, clearing out the board.

-Arcege

--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------

```