Stop Using ‘or’ to Test Multiple Values Against a Variable in Python
Use the ‘in’ keyword for multiple comparisons
Stop Using “or” to Test Multiple Values Against a Variable in Python
Use the “in” keyword for multiple comparisons
If you’ve ever needed to check that a variable is equal to one of many possible values, you’ve probably written something like this:if x == 1 or x == 10 or x == 100:
pass
Well, there’s a better way!
Let’s go through how to use the in keyword instead of or to recreate the expression above.
What is the “in” Keyword?
The keyword in can be used to search through a sequence and will return either True or False depending on whether the left operand is found.
Here’s a simple example, checking for the letter e in a string:result = 'e' in 'The'
print(result) # True
Since the in keyword can be used with any sequence, we place all the values that we’re comparing with our variable into a single sequence. The question is now, which data type is best?
The initial response may be to use a list:if x in [1,10,100]:
pass
This works fine, although we can squeeze better performance out by using a tuple or even a set:# tuple example
if x in (1,10,100):
pass# set example
if x in {1,10,100}:
pass
Using the in keyword is not only less syntax to initially type, it’s easier to read and maintain. Feel free to create your tuple on a separate line and use it in the if statement, to keep your code more readable.matches = (1,10,100)if x in matches:
pass
Remember, this technique is only appropriate for equality comparisons. However, you can invert the expression to effectively test for inequality:if x not in (1,10,100):
pass
When simple becomes overbearing, find ways to write code that are more concise, easy to read, and maintainable.
I hope this was helpful, share your thoughts and comments below!