How to test multiple variables for equality against a single value?
In Python, you can test multiple variables for equality against a single value using the == operator.
In Python, you can test multiple variables for equality against a single value using the == operator. Here is an example code snippet:
test multiple variables for equality against a single value using a chain of == operators in Python
a = 5
b = 10
c = 15
if a == b == c:
print("All variables are equal")
else:
print("Variables are not equal")
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also use the all() function along with a generator expression to check if all variables are equal to a single value:
test multiple variables for equality against a single value using the all function in Python
if all(var == 5 for var in (a, b, c)):
print("All variables are equal to 5")
else:
print("Variables are not equal to 5")In this example, the all() function checks if all elements of the generator expression (var == 5 for var in (a, b, c)) are true, and returns True if they are.
It's also worth mentioning that you can use is keyword to check if multiple variables are pointing to the same object in memory.
the is keyword also tests equality in Python
a = [1,2,3]
b = a
c = [1,2,3]
if all(var is a for var in (a, b, c)):
print("All variables are pointing to the same object")
else:
print("variables are pointing to different object")