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. Here is an example code snippet:
a = 5
b = 10
c = 15
if a == b == c:
print("All variables are equal")
else:
print("Variables are not equal")
Watch a video course
Python - The Practical Guide
You can also use the all()
function along with a generator expression to check if all variables are equal to a single value:
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.
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")