Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Connect Four: Having trouble getting the two indexes for lists inside a list

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) 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading