Member-only story
Stop Using “or” to Check Multiple Conditions in Python
There is a more sophisticated solution
We all are familiar with using these 2 lines to check whether a variable satisfies one or multiple equalities.
Nothing is more natural than coding this way, i.e., separating each condition with or
logical operator. But that is not the whole story.
As I said at the beginning of the article, there is a sophisticated solution. This can be also a better solution, or not. It depends on your aspect and how you define ‘better’. I’ll give a couple of approaches, and we’ll analyze their strengths and weaknesses.
“in” operator in Python
The in
keyword essentially has two usages in Python:
1: To iterate through a sequence:
Example:
Result:
winter
spring
summer
autumn
2: To check if a value exists in a sequence (string, tuple, list, etc.) or not. According to the existence of a value, it returns True
or False
.
Example 1:
Result:
True
False
Example 2:
Now let’s take a look at the subtitle of this section: