1

I would like to know if I have if-else or if-elif-elif-....-else condition like below:

if conditionA:
    do A
elif conditionB:
    do B
elif conditionC:
    do C
...
...
...
else:
    do z

Q1. If I already know that my condition resolve in conditionC for 99% of time, putting that condition as first one (instead of conditionA) would make my code more efficient?

Q2. Similarly, should I prioritize my statements that way, if Q1 is true?

Apologies if the question has already been asked. I might not have found the proper vocabulary to search for this.

Thank You.

Jay Patel
  • 137
  • 7

2 Answers2

3

Q.1 and Q.2: Yes

According to Python documentation

An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.

which means as soon as code executes a True condition, it will exit the if … elif … elif … sequence.

ameydev
  • 126
  • 1
  • 1
  • 6
1

You see these conditions take O(1) time, you can say it is negligible to compared to the other code you have written along with it, so like if you have a code along with it which have two nested loops O(n^2) then the conditions are negligible time taking compared to your overall algo.

Moreover, this tells you the estimated complexity.

But other wise i'd say you must put it to condition A, because what you put in these conditions may have their respective time complexities.

suppose you have sub-string search using in operator in python, it goes like.

st = 'hello' * (2 ** 999) # hellohellohellohe...    

if 'hey' in st: 
    print('hey, I found it')

else:
    print('well..')

it takes around θ(n) and O(MN), where m is string and n is sub-string to be compared.

have a look at this python substring.

So, it wrap this up, the preferred way would be to it on condition A.

P.hunter
  • 1,345
  • 2
  • 21
  • 45