when to use if vs elif in python

Question:

If I have a function with multiple conditional statements where every branch gets executed returns from the function. Should I use multiple if statements, or if/elif/else? For example, say I have a function:

def example(x):
    if x > 0:
        return 'positive'
    if x < 0:
        return 'negative'
    return 'zero'

Is it better to write:

def example(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

Both have the same outcome, but is one more efficient or considered more idiomatic than the other?

Edit:

A couple of people have said that in the first example both if statements are always evaluated, which doesn’t seem to be the case to me

for example if I run the code:

l = [1,2,3]

def test(a):
    if a > 0:
        return a
    if a > 2:
        l.append(4)

test(5)

l will still equal [1,2,3]

Answers:

In some cases, elif is required for correct semantics. This is the case when the conditions are not mutually exclusive:

if x == 0:   result = 0
elif y == 0: result = None
else:        result = x / y

In some cases it is efficient because the interpreter doesn’t need to check all conditions, which is the case in your example. If x is negative then why do you check the positive case? An elif in this case also makes code more readable as it clearly shows only a single branch will be executed.

Answered By: perreal

elif is a bit more efficient, and it’s quite logical: with ifs the program has to evaluate each logical expression every time. In elifs though, it’s not always so. However, in your example, this improvement would be very, very small, probably unnoticeable, as evaluating x > 0 is one of the cheapest operations.

When working with elifs it’s also a good idea to think about the best order. Consider this example:

if (x-3)**3+(x+1)**2-6*x+4 > 0:
    #do something 1
elif x < 0:
    #do something 2

Here the program will have to evaluate the ugly expression every time! However, if we change the order:

if x < 0:
   #do something 2
elif (x-3)**3+(x+1)**2-6*x+4 > 0:
   #do something 1

Now the program will first check if x < 0 (cheap and simple) and only if it isn’t, will it evaluate the more complicated expression (btw, this code doesn’t make much sense, it’s just a random example)

Also, what perreal said.

Answered By: Dunno

Check this out to understand the difference:

>>> a = 2
>>> if a > 1: a = a+1
...
>>> if a > 2: a = a+1
...
>>> a
4

versus

>>> a = 2
>>> if a > 1: a = a+1
... elif a > 2: a = a+1
...
>>> a
3

The first case is equivalent to two distinct if‘s with empty else statements (or imagine else: pass); in the second case elif is part of the first if statement.

Answered By: marco

I’ll expand out my comment to an answer.

In the case that all cases return, these are indeed equivalent. What becomes important in choosing between them is then what is more readable.

Your latter example uses the elif structure to explicitly state that the cases are mutually exclusive, rather than relying on the fact they are implicitly from the returns. This makes that information more obvious, and therefore the code easier to read, and less prone to errors.

Say, for example, someone decides there is another case:

def example(x):
    if x > 0:
        return 'positive'
    if x == -15:
        print("special case!")
    if x < 0:
        return 'negative'
    return 'zero'

Suddenly, there is a potential bug if the user intended that case to be mutually exclusive (obviously, this doesn’t make much sense given the example, but potentially could in a more realistic case). This ambiguity is removed if elifs are used and the behaviour is made visible to the person adding code at the level they are likely to be looking at when they add it.

If I were to come across your first code example, I would probably assume that the choice to use ifs rather than elifs implied the cases were not mutually exclusive, and so things like changing the value of x might be used to change which ifs execute (obviously in this case the intention is obvious and mutually exclusive, but again, we are talking about less obvious cases – and consistency is good, so even in a simple example when it is obvious, it’s best to stick to one way).

Answered By: Gareth Latty

In general (e.g. your example), you would always use an if..elif ladder to explicitly show the conditions are mutually-exclusive. It prevents ambiguity, bugs etc.

The only reason I can think of that you might ever not use elif and use if instead would be if the actions from the body of the preceding if statement (or previous elif statements) might have changed the condition so as to potentially make it no longer mutually exclusive. So it’s no longer really a ladder, just separate concatenated if(..elif..else) blocks. (Leave an empty line between the separate blocks, for good style, and to prevent someone accidentally thinking it should have been elif and ‘fixing’ it)

Here’s a contrived example, just to prove the point:

if total_cost>=10:
    if give_shopper_a_random_discount():
        print 'You have won a discount'
        total_cost -= discount
    candidate_prime = True

if total_cost<10:
    print 'Spend more than $10 to enter our draw for a random discount'

You can see it’s possible to hit both conditions, if the first if-block applies the discount, so then we also execute the second, which prints a message which would be confusing since our original total had been >=10.

An elif here would prevent that scenario.
But there could be other scenarios where we want the second block to run, even for that scenario.

if total_cost<10:
    <some other action we should always take regardless of original undiscounted total_cost>
Answered By: smci

In regards to the edit portion of your question when you said:
“A couple of people have said that in the first example both if statements are always evaluated, which doesn’t seem to be the case to me”

And then you provided this example:

l = [1,2,3]

def test(a):
    if a > 0:
        return a
    if a > 2:
        l.append(4)

test(5)

Yes indeed the list l will still equal [1,2,3] in this case, ONLY because you’re RETURNING the result of running the block, because the return statement leads to exiting the function, which would result in the same thing if you used elif with the return statement.

Now try to use the print statement instead of the return one, you’ll see that the 2nd if statement will execute just fine, and that 4 will indeed be appended to the list l using append.

Well.. now what if the first ifstatement changes the value of whatever is being evaluated in the 2nd if statement?

And yes that’s another situation. For instance, say you have a variable x and you used if statement to evaluate a block of code that actually changed the x value.
Now, if you use another if statement that evaluates the same variable x will be wrong since you’re considering x value to be the same as its initial one, while in fact it was changed after the first if was executed. Therefore your code will be wrong.

It happens pretty often, and sometimes you even want it explicitly to be changed. If that’s how you want your code to behave, then yes you should use multiple if‘s which does the job well. Otherwise stick to elif.

In my example, the 1st if block is executed and changed the value of x, which lead to have the 2nd if evaluates a different x (since its value was changed).

That’s where elif comes in handy to prevent such thing from happening, which is the primary benefit of using it.
The other secondary good benefit of using elif instead of multiple if‘s is to avoid confusion and better code readability.

Answered By: Fouad Boukredine

Consider this For someone looking for a easy way:

>>> a = ['fb.com', 'tw.com', 'cat.com']
>>> for i in a:
...      if 'fb' in i:
...          pass
...      if 'tw' in i:
...          pass
...      else:
...          print(i)

output:

fb.com

cat.com

And

>>> a = ['fb.com', 'tw.com', 'cat.com']
>>> for i in a:
...      if 'fb' in i:
...          pass
...      elif 'tw' in i:
...          pass
...      else:
...          print(i)

Output:

cat.com

‘If’ checks for the first condition then searches for the elif or else, whereas using elif, after if, it goes on checking for all the elif condition and lastly going to else.

Answered By: Ujjwal Singh Baghel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.