'Why does this order of a Python if statement matter?

This is my code for a Leetcode problem, and I'm wondering why one if statement works but the other does not.

def validWordSquare(words):
    for row in range(len(words)):
        for column in range(len(words[row])):
            # if row >= len(words[column]) or column >= len(words) or words[row][column] != words[column][row]:  # doesn't work
            if column >= len(words) or row >= len(words[column]) or words[row][column] != words[column][row]:  # works
                return False

    return True

words = ["abc","b"]
print(validWordSquare(words))


Solution 1:[1]

def validWordSquare(words):
    for row in range(len(words)):
        for column in range(len(words[row])):
            print(f'{row=} {column=}')
            if row >= len(words[column]) or column >= len(words) or words[row][column] != words[column][row]:  # doesn't work
            # if column >= len(words) or row >= len(words[column]) or words[row][column] != words[column][row]:  # works
                return False

    return True

words = ["abc","b"]
print(validWordSquare(words))

Testing output Notice column = 2 is out of range in the code.

row=0 column=0
row=0 column=1
row=0 column=2
Traceback (most recent call last):
  File "C:\Users\ctynd\AppData\Roaming\JetBrains\PyCharm2021.3\scratches\scratch.py", line 12, in <module>
    print(validWordSquare(words))
  File "C:\Users\ctynd\AppData\Roaming\JetBrains\PyCharm2021.3\scratches\scratch.py", line 5, in validWordSquare
    if row >= len(words[column]) or column >= len(words) or words[row][column] != words[column][row]:  # doesn't work
IndexError: list index out of range

Evaluating column >= len(words) first prevents row >= len(words[column]) from being evaluated if column is out of range for that expression. This is called short-circuit evaluation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CryptoFool