Trick 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 =…