Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python efficiency of and vs multiple ifs

Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like

if expr1 == expr2 and expr3==expr4:
  dostuff()

different from an efficiency standpoint then:

if expr1 == expr2:
  if expr3 == expr4:
    dostuff()

My very basic testing does not reveal a difference, but does someone with more knowledge (or at least more thorough testing) have a definitive answer?

like image 861
TimothyAWiseman Avatar asked Aug 20 '10 17:08

TimothyAWiseman


People also ask

Can you have 2 IFS in Python?

Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn't true, there's another one that you want to test.

What is the difference between multiple if and Elif in Python?

Multiple 'if' statements get checked one after another with no regard to the former's results. 'Elif' acts as 'else if', so is checked only in the 'else' case - that is only then, if the first 'if' is False.

Why is it better to use Elif instead of if?

The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.


1 Answers

This isn't enough of a performance difference, if any, to affect your decision. IMO, the decision here should be made purely from a readability perspective. The first is generally more standard, I think, but there are situations when the second might be clearer. Choose the method that best gets your intent across.

like image 127
froadie Avatar answered Oct 19 '22 16:10

froadie