How to test multiple variables for equality against a single value?
You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:
if x == 1 or y == 1 or z == 1:
x
and y
are otherwise evaluated on their own (False
if 0
, True
otherwise).
You can shorten that using a containment test against a tuple:
if 1 in (x, y, z):
or better still:
if 1 in {x, y, z}:
using a set
to take advantage of the constant-cost membership test (i.e. in
takes a fixed amount of time whatever the left-hand operand is).
Explanation
When you use or
, python sees each side of the operator as separate expressions. The expression x or y == 1
is treated as first a boolean test for x
, then if that is False, the expression y == 1
is tested.
This is due to operator precedence. The or
operator has a lower precedence than the ==
test, so the latter is evaluated first.
However, even if this were not the case, and the expression x or y or z == 1
was actually interpreted as (x or y or z) == 1
instead, this would still not do what you expect it to do.
x or y or z
would evaluate to the first argument that is 'truthy', e.g. not False
, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).
So for the values x = 2; y = 1; z = 0
, x or y or z
would resolve to 2
, because that is the first true-like value in the arguments. Then 2 == 1
would be False
, even though y == 1
would be True
.
The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3
would fail for the same reasons. Use x == 1 or x == 2 or x == 3
or x in {1, 2, 3}
.
Check if multiple variables have the same value
If you have an arbitrary sequence, use the all()
function with a generator expression:
values = [x, y, z] # can contain any number of values
if all(v == 1 for v in values):
otherwise, just use ==
on all three variables:
if x == y == z == 1:
If you only needed to know if they are all the same value (regardless of what value that is), use:
if all(v == values[0] for v in values):
or
if x == y == z:
How to compare multiple variables to the same value?
You want to test a condition for all
the variables:
if all(x >= 2 for x in (A, B, C, D)):
print(A, B, C, D)
This should be helpful if you're testing a long list of variables with the same condition.
If you needed to check:
if A, B, C, or D >= 2:
Then you want to test a condition for any
of the variables:
if any(x >= 2 for x in (A, B, C, D)):
print(A, B, C, D)
Compare multiple values against the same variable
Use indexOf
with array of values
var valArr = ["kivi","apples","lychee","banana.C","mangos"];
if(valArr.indexOf(val) > -1){
.......
}
Most efficient way to compare a variable to multiple values?
If the values you want to check are sufficiently small, you could create a bit mask of the values that you seek and then check for that bit to be set.
Suppose, you care about a couple of groups.
static const unsigned values_group_1 = (1 << 1) | (1 << 2) | (1 << 3);
static const unsigned values_group_2 = (1 << 4) | (1 << 5) | (1 << 6);
static const unsigned values_group_3 = (1 << 7) | (1 << 8) | (1 << 9);
if ((1 << value_to_check) & values_group_1) {
// You found a match for group 1
}
if ((1 << value_to_check) & values_group_2) {
// You found a match for group 2
}
if ((1 << value_to_check) & values_group_3) {
// You found a match for group 3
}
This approach works best for values that don't exceed the natural size your CPU likes to work with. This would typically be 64 in modern times, but may vary depending upon the specifics of your environment.
Compare multiple values in one condition
You can create an usefull extension function:
public static bool EqualsAll<T>(this T val, params T[] values)
{
return values.All(v => v.Equals(val));
}
call it like:
bool res = 123.EqualsAll(int1,int2,int3);
Related Topics
Complexity of *In* Operator in Python
"Pythonic" Method to Parse a String of Comma-Separated Integers into a List of Integers
In Pytest, What Is the Use of Conftest.Py Files
Multiple Variables in a 'With' Statement
Find First Element in a Sequence That Matches a Predicate
Absolute VS. Explicit Relative Import of Python Module
How to Determine Whether a Year Is a Leap Year
How to Compare String and Integer in Python
Unicodedecodeerror When Redirecting to File
How to Convert CSV File to Multiline JSON
Timeit Versus Timing Decorator
Problems with Pip Install Numpy - Runtimeerror: Broken Toolchain: Cannot Link a Simple C Program
How to Do/Workaround a Conditional Join in Python Pandas
Optimal Hdf5 Dataset Chunk Shape for Reading Rows
Saving a Figure After Invoking Pyplot.Show() Results in an Empty File