1

If I need to evaluate multiple conditional statements, is it faster to use a nested series of if statements or to place all conditions within a single if statement separated by and? For example:

x=[True, False, False, True]
y=[0,1,2,3]

for i in list(range(len(x))):
    if x[i] and expensive_computation(y[i]):
        do_something

    if x[i]:
        if expensive_computation(y[i]):
            do_something

Will the first conditional statement if x[i] and expensive_computation(y[i]) check the Boolean value of expensive_computation(y[i]) if x[i] is already False?

apogalacticon
  • 709
  • 1
  • 9
  • 19
  • No, `and` short-circuits. – Ry- Mar 29 '18 at 19:27
  • `and` becomes `if` in the byte code so they are mostly equivalent. Try it boths ways then use `dis.dis()` to check. – tdelaney Mar 29 '18 at 19:30
  • Thanks for the quick answer and for providing a link to a similar question. I had not heard of the term short-circuiting before, and so I did not discover this question in my search. – apogalacticon Mar 29 '18 at 19:43

0 Answers0