How can I compare a variable within a list of lists by reading/changing their content in Python?

Asked

Viewed 23 times

0


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

p_move = input('Enter your move: ')) # p_move = '4'
for row in board:
    for column in row:
        if p_move == board[row][column]: # '4' == board[1][0]
           board[row][column] = 'O' # board[1][0] = 'O'

(TypeError: list indices must be integers or slices, not list)

1 answer

0


Are you confusing the one-line index with the element (list) one-line.

In your loop:

for row in board:
    for column in row:
        if p_move == board[row][column]:

board is a list of lists, so when iterating on it, each element (row) will be a list.

When writing board[row], you effectively write (for the first iteration) board[[['1','2','3']], causing the error you see.

A simple way to fix this is to use range and len, and then iterate on a numerical sequence:

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

n_rows = len(board)
n_cols = len(board[0])  # assumimos que board é quadrada

p_move = input('Enter your move: ')
for row in range(n_rows):
    for column in range(n_cols):
        if p_move == board[row][column]:
           board[row][column] = 'O'
  • Thanks I was trying earlier to wear something like this python

for row in len(board):
 for column in len(row):

Browser other questions tagged

You are not signed in. Login or sign up in order to post.