Skip to main content

How To Simplify IF In Python

Using conditionals or say IF-ELSE statement is quite common when developing any application and based on the programming language, the syntax to handle such conditionals varies but the underline concept remains the same.

In this article, I’ll show you how to write an IF statement in Python to check if a given item is present in the collection or not.

Have a look at the traditional way to achieve the same:

fruits = [‘apple’,’orange’,’banana’,’mango’]
fruit = ‘mango’
if(fruit==’apple’ or fruit==’orange’ or fruit==’banana’ or fruit==’mango’):
print(‘Found the fruit’)

In the above snippet, we have a collection holding multiple fruits and a variable holding one fruit. The idea here is to check whether the given fruit exists in the collection or not. 

There is no problem with the above code but we do have a way to optimize it and by optimizing the code, we can achieve the below benefits:

  • less number of lines of code
  • less error prone
  • no need to change code, if more items are added to the collection tomorrow
Here is the version of optimized code:

fruits = [‘apple’,’orange’,’banana’,’mango’]
fruit = ‘mango’
if fruit in fruits:
print(“Found the fruit”)

If you closely look at this code, you will realize that IF condition is simplified a lot. Isn’t it?

Well, if you find anything unclear, please feel free to check out the demonstration of this article on my YouTube channel:


I hope you enjoyed learning this quick tip today.

Comments