Check if multiple variables have same value in Python
In this tutorial, we are going to learn about how to check if a multiple variables are equal to same value in Python with the help of examples.
Consider, that we have the following variables in our code:
x = 11
y = 11
z = 11
Now, we need to check the above variables are equal to same value or not in Python.
Checking if multiple variables are equal
To check if multiple variables are equal to same value, we can use the built-in all()
function in Python.
The all()
function returns True if all items in the iterable are true. Otherwise, it returns false.
Here is an example:
x = 11
y = 11
z = 11
if all(item == 11 for item in [x, y, z]):
print('Multiple variables are equal')
else:
print('Some of the variables are not equal')
Output:
'Multiple variables are equal'
In the above code,
-
We have first added the variables into the list.
-
Then iterated over the list using
in
operator. -
On each iteration, we have checked if the
item == 11
.
Finally, the all()
function returns True
if the all items in the list returns true, otherwise false is returned.
If it returns True
then it should prints the Multiple variables are equal
, if at least one of the variables are not equal then it returns False
and prints Some of the variables are not equal
.
Using equality operator (==)
We can use the equality operator (==) in Python to check if a multiple variable are having the same value.
Here is an example:
x = 11
y = 11
z = 11
if x == y == z:
print('Multiple variables are equal')
else:
print('Some of the variables are not equal')
Checking Some of the variables are not equal
x = 11
y = 11
z = 10
if all(item == 11 for item in [x, y, z]):
print('Multiple variables are equal')
else:
print('Some of the variables are not equal')
Output:
'Some of the variables are not equal'
In the above code, it prints “Some of the variables are not equal” because the variable z
is assigned to 10
.