Home >Backend Development >Python Tutorial >Why Does `a == x or y or z` Always Evaluate to True in Python?
The "a == x or y or z" Fallacy
When attempting to compare a variable against multiple values, it's tempting to use Python's logical operators, as in:
if a == x or y or z: # Incorrect
However, this expression will always evaluate to True, regardless of the value of a. This is because the "or" operator in this context does not behave as expected.
How the "or" Operator Works
Python's "or" operator (|) will evaluate to True if any of its operands are True. So in the above expression, since one of x, y, or z is always True (a non-empty value is True in Python), the expression evaluates to True regardless of the value of a.
Correct Ways to Compare to Multiple Values
To correctly compare a variable to multiple values, there are several options:
Use explicit "or" operators to compare against each value separately:
if a == x or a == y or a == z: # Correct
Create a set or list of valid values and use the "in" operator to check membership:
if a in {"Kevin", "Jon", "Inbar"}: # Correct
Use a generator expression with "any()" to explicitly check each value:
if any(a == auth for auth in ["Kevin", "Jon", "Inbar"]): # Correct
Consider Performance
For performance, using sets or lists with the "in" operator is typically the fastest option. Generator expressions using "any()" are the most verbose and slowest.
Example Usage
To grant access only to authorized users:
authorized_names = {"Kevin", "Jon", "Inbar"} name = input("Please enter your name: ") if name in authorized_names: print("Access granted.") else: print("Access denied.")
The above is the detailed content of Why Does `a == x or y or z` Always Evaluate to True in Python?. For more information, please follow other related articles on the PHP Chinese website!