Search code examples
pythonfor-loopif-statementminimax

Most effective Python loop with if statements


I am building a minimax function and need to make some checks for each iteration. I want the iterations to be as efficient as possilbe to be able to increase the search depth and therefore want to know how Python if-statements works in for loops. Let me give you a simplified example:

# Example 1

def test(x_start, y_start):

    for xdir, ydir in [[1, -1], [1, 1], [-1, 1], [-1, -1]]:
        x, y = x_start, y_start
        x += xdir
        y += ydir
        if not is_on_board(x, y) and board[x][y].type == 'full':
            continue

# Example 2

def test(x_start, y_start):

    for xdir, ydir in [[1, -1], [1, 1], [-1, 1], [-1, -1]]:
        x, y = x_start, y_start
        x += xdir
        y += ydir
        if not is_on_board(x, y):
            if not board[x][y].type == 'full':
                continue

Is it more efficient to go for Example 2 since it will in some cases skip the first if statement based on that the position is not on the board and don't have to make the additional check for board type?

In my real code there are more and-statements with both function and variable checks which can be relatively time consuming. Therefore I want to know if it is more efficient to break the and-statements into more if statements as in Example 2, or if it doesn't really matter? Generally speaking.


Solution

  • Most programming languages including Python will 'short circuit' boolean logic checks - that means that they don't continue evaluating once the truth value is known. The difference between multiple if statements or and/or statements is negligible and you should think about which is more readable; on the other hand the ordering of the checks can make a difference if some of them are more expensive or more informative.