ChickenSoup439
ChickenSoup439

Reputation: 11

How to check the type of an element in a 2d array in Python

I've been trying to make a tic-tac-toe game and so far, I've only created a function that's supposed to print out the board:

    board = [[1,2,3],[4,5,6],[7,8,9]]

    def drawboard(board):
        for row in board:
            for item in row:
                if type(board[row][item]) == "int":
                    print(str(board[row][item]))
                    print("|")
                else:
                    print(board[row][item])
                    print("|")
            print("\n")
            print("------")
            print("\n")

    drawboard(board)

As you can see, a part of my function is checking the type of an element inside of a list inside of a list but it's giving me an error:

Traceback (most recent call last): File "/Users/Tony/Desktop/coding things/tic tac toe.py", line 22, in drawboard(board)\ File "/Users/Tony/Desktop/coding things/tic tac toe.py", line 12, in drawboard if type(board[row][item]) == "list": TypeError: list indices must be integers or slices, not list

Upvotes: 0

Views: 1039

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

There are a few problems here:

  1. if you iterate over a list, you iterate over the elements of the list, not the indices; and
  2. if you query for type(..) you do not get a string as return element, but a reference to the class. So you can fix this like:
    board = [[1,2,3],[4,5,6],[7,8,9]]

    def drawboard(board):
        for row in board:
            for item in row:
                if type(item) == int:
                    print(str(item))
                    print("|")
                else:
                    print(item)
                    print("|")
            print("\n")
            print("------")
            print("\n")

    drawboard(board)

Since non-str items are typically str(..)-ed when you call print on them, we can even merge the if and else branch into:

def drawboard(board):
    for row in board:
        for item in row:
            print(item)
            print("|")
        print("\n")
        print("------")
        print("\n")

drawboard(board)

If you proceed with this typecheck, typically checking for type equality is not really a good idea either. Since if the element is subclassed, the type is no longer int. You then better use isinstance(..).

Upvotes: 1

Mohd
Mohd

Reputation: 5613

In your for loops, row and item aren't indices, you only need to check the type of item, to do that you need to change this line:

if type(board[row][item]) == "int":

to

if isinstance(item, int):

After fix:

def drawboard(board):
    for row in board:
        for item in row:
            if isinstance(item, int):
                print(str(item))
                print("|")
            else:
                print(item)
                print("|")
        print("\n")
        print("------")
        print("\n")

Upvotes: 1

Related Questions