Search code examples
pythonexecution

python order of evaluation with ands in if statements


It's common to put in a check for None or have similar error catch. Sometimes you also need another if statement that depends on x:

if x == None:
   if x[0]>0:
     ... # some code

Can you safely combine the if statements like this (for code brevity)?

if x != None and x[0]>0:
     ... # some code

Or does the interpreter not guarantee the order of evaluation and stopping after the first False?


Solution

  • Yes it is safe, because the operators and and or short-circuits.

    Note:

    • One recommendation would be to use is if you want to check if an object is None:

      if x is not None and x[0] > 0:
          # ...