Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If vs. Elif in Python, which is better?

I am reading Grokking Algorithms, which seems to be a highly recommended book. I am looking at the first algorithm for "binary search" and the guy uses two "ifs" instead of a "if" and "elif". Would using two "ifs" be better or faster?

def binary_search(list, item):
    low = 0
    high = len(list) - 1

    while low <= high:
        mid = (low + high)
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

my_list = [1,3,5,7,9]
like image 513
we_are_all_in_this_together Avatar asked Oct 28 '25 14:10

we_are_all_in_this_together


1 Answers

example1

>>> def foo():
    a = 10
    if a == 10:
        print("condition1")
    elif a == 10:
        print("condition2")
    else:
        print(0)    
>>> foo()
condition1
>>> 

elif is guaranteed not to run when if is true.

example2

def foo():
    a = 10
    if a == 10:
        print("condition1")
    if a == 10:
        print("condition2")
    else:
        print(0)
>>> foo()
condition1
condition2
>>> 

example3 modify if statement of example2.

if a == 10:
    print("condition1")
    return a

output

>>> foo()
condition1
10

So, in your case adding a return in first if statement has similar operation like an if-elif block. the (return a) is preventing the second if statement to be executed in example3.

like image 97
sage07 Avatar answered Oct 30 '25 10:10

sage07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!