As other answers mentioned, an elif is not necessary after an if that does a return. But they didn't cover the performance impact. I thought it would be interesting to test.
Turns out, it can be a tad faster to use if/elif/else instead of separate if's.
from timeit import timeit
import random
def count_items_ifelifelse(items, threshold):
below, on, above = 0, 0, 0
for item in items:
if item > threshold:
above += 1
elif item < threshold:
below += 1
else:
on += 1
return below, on, above
def count_items_ififif(items, threshold):
below, on, above = 0, 0, 0
for item in items:
if item > threshold:
above += 1
if item < threshold:
below += 1
if item == threshold:
on += 1
return below, on, above
def generate_items_and_threshold(count=100_000):
"""List of reproducible random numbers to test with. Set threshold at half"""
items = list(range(count))
random.Random(123).shuffle(items)
threshold = count // 2
return items, threshold
def run_test():
t1 = timeit(
"count_items_ifelifelse(i, t)",
setup="from __main__ import count_items_ifelifelse, generate_items_and_threshold; i, t = generate_items_and_threshold()",
number=1000,
)
print("count_items_ifelifelse: {:.2f}".format(t1))
t2 = timeit(
"count_items_ififif(i, t)",
setup="from __main__ import count_items_ififif, generate_items_and_threshold; i, t = generate_items_and_threshold()",
number=1000,
)
print("count_items_ififif: {:.2f}".format(t2))
if __name__ == "__main__":
run_test()
This outputs (Python 3.8.2, Windows):
count_items_ifelifelse: 6.69
count_items_ififif: 8.71
Roughly 20% faster, because of more unnecessary if evaluations each loop. The other side of it is that for if/elif/else the performance will vary based on how the data is sorted, and whether it checks the most occurring condition first.