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’)
- 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, do not forget to check out the demonstration of this article on my YouTube channel named Shweta Lodha.