Home > Software design >  Python Connect Four: Having trouble getting the two indexes for lists inside a list
Python Connect Four: Having trouble getting the two indexes for lists inside a list

Time:04-17

I am trying to create a very simple connect four game in python. I have a list named connect four that contains multiple lists of each row in the board. Each of these lists has 7 items in it. I have a for loop to go through each row in the connect four list and then another to go through each item in each row. I am trying to get the index for every item on the board. Here is my code to attempt this, but it is not returning the correct indexes.

for x in connect_four:
  row = connect_four.index(x)
  for item in x:
    col = x.index(item)
    print("The row is "   str(row))
    print("The column is "   str(col))

Here is my code to create the list in the first place.

connect_four = []
for row in range(6):
  connect_four.append(["|___|"] * 7)
  
def print_board(board):
  for row in board:
    print("".join(row))

print_board(connect_four) 

CodePudding user response:

See if this gives you a hint on how to enumerate through a 2D array like this:

for y,row in enumerate(connect_four):
  for x,item in enumerate(row):
    print( f"The contents of {y},{x} is {item}." )

Remember that index returns you the index of the FIRST match in that row. That's almost never going to be what you want in this context.

  • Related