Search code examples
pythonloopscell

For loops using "cell" in Python, Index problem


code When I try to travel through a 2D array,and to record the (i,j) pairs that I want, I find that the index function always return the same j in each different loop. I think in each loop, "cell" should be different, even though they likely to have the same value.Really confused.

code Like I said, you can see that instead of a [(0,0),(0,1),(0,2),...], the result is in the picture above.


Solution

  • index is the wrong tool here. Remember that index always returns the FIRST match. If you have several occurrences of 0, it's only going to return the index of the first one.

    You need to use enumerate, so you track the indexes as well as the contents:

    for y,row in enumerate(board):
        for x,cell in enumerate(row):
            if cell == EMPTY:
                actions.append( (y, x) )