pythonpython-3.x

For loop with list indexes Python


I have this code that is supposed to print each item in the main list on a new row with a corresponding row number. In the below code it works fine:

my_list = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
for item in my_list:
    print(my_list.index(item)+1, item)

However when I try to implement it into a "tic-tac-toe" game I'm making it doesn't work.

Here is the problematic code:

def showGrid(y, x, "X"):
    board[y][x] = "X"
    print("  x x x")
    for row in board:
        print(board.index(row)+1, sub("[,']", "", str(row)[1:-1]))

The output of the code above is not the same as the first example and instead it gives a random output depending on what the y and x values are.

For example if y and x were both set to 1 the output is:

  x x x
1 X - -
2 - - -
2 - - -

And when x and y are both set to 2 the output is:

  x x x
1 - - -
2 - X -
1 - - -

What I want it to be is 1 2 3 going down.

If there is a page that covers this please link it. If more of the code is needed please say so. Otherwise thanks in advance. :)


Solution

  • You don't want to use the index method for this, for 2 reasons: (1) It is inefficient to keep searching for the current list index, and (2) if there are duplicate entries in the list, it will always return the index of the first matching element, which is what's causing the problems you're seeing.

    Try this instead:

    def showGrid(y, x, "X"):
        board[y][x] = "X"
        print("  x x x")
        for ix, row in enumerate(board):
            print(ix+1, sub("[,']", "", str(row[1:-1]))
    

    The way this works is enumerate generates a tuple for each list element. The first value of the tuple is the list index, and the second value of the tuple is the list element.