Search code examples
pythonif-statementlogical-operators

Performance difference between two if statements?


I asked myself if it makes a performance difference if I use an if statement with x conditions, or x if statements with only 1 condition each.

so for example:
if statement with 3 conditions:

if a == 0 and b == 0 and c == 0:
    #do something

3 if statements with just one condition each:

if a == 0:
    if b == 0:
        if c == 0:
            #do something

Why do I want to know this?
I have an if statement with around 30 conditions and my code gets really messi, so I thought about splitting my if-statement in half. I think that the results of this examples will be the same, but I don't know if there would be a noticeable performance difference if a == 1. Would the program check all 3 conditions in the first example even if the first one (a is 1 not 0) is false?


Solution

  • With the given example, there won't be any difference in performance, even with if a == 0 and b == 0 and c == 0: it won't check b == 0 when the initial condition a == 0 itself is False. But considering the minimal lines of code & readability, if a == 0 and b == 0 and c == 0: would be the better option.