Long if vs in Operator

Posted by Afsal on 01-Jul-2022

Hi Pythonistas!

Today we are going to learn another performance optimization technique in Python. Replacing long if check with in operator. 

Consider the example below

import random
import timeit

def long_condition_check():
    number = random.randint(1, 10)
    if (number == 2 or number == 4 or number == 6 or number == 8 or number == 10):
        return True
    return False

def using_in_operator():
    number = random.randint(1, 10)
    return number in [2, 4, 6, 8, 10]

time_taken = timeit.timeit(long_condition_check, number=1000_000)
print("Time taken for long if: ", time_taken)

time_taken = timeit.timeit(using_in_operator, number=1000_000)
print("Time taken for in operator: ", time_taken)

Output

Time taken for long if:  0.6203273379996972
Time taken for in operator:  0.5827239469999768

Why

If we analyse the code we can see that in long if we have 5 operations but second case that is only one operation which makes this more faster.

Hope you have learned something from this post please share your feedback at afsal@parseltongue.co.in