Rallph
Rallph

Reputation: 19

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 corasponding 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 impliment it into a "tic-tac-toe" game im making it dosnt work. Here is the problimatic 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. :)

Upvotes: 0

Views: 86

Answers (2)

Tom Karzes
Tom Karzes

Reputation: 24052

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.

Upvotes: 4

Moe
Moe

Reputation: 510

board.index(row) returns the first index at which row is found. In this case, the first index is 0 because it contains - - -. You could avoid using the list.index function by looping through a range, for example:

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

Upvotes: 0

Related Questions