Python - check if multiple variables have the same value

I have a set of three variables x, y, z, and I want to check if they all have the same value . In my case, the value will be either 1 or 2, but I only need to know if they are all the same. I am currently using

if 1 == x and 1 == y and 1 == z: sameness = True 

We are looking for the answer that I found:

 if 1 in {x, y, z}: 

However it works like

 if 1 == x or 1 == y or 1 == z: atleastOneMatch = True 

Is it possible to check if 1 is in each: x, y and z? Even better, is there a more concise way of checking simply if x, y and z are the same value?

(if that matters, I'm using python 3)

+6
source share
6 answers

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 == for all three variables:

 if x == y == z == 1: 

If you only need to know if they are the same (no matter what value this value is), use:

 if all(v == values[0] for v in values): 

or

 if x == y == z: 
+13
source

To check if they are all the same (1 or 2):

 sameness = (x == y == z) 

Brackets are optional, but I think this improves readability.

+3
source

How about this?

 x == y == z == 1 
+2
source

Another way:

 sameness = all(e == 1 for e in [x, y, z]) 
+1
source

You can use something similar to what you have:

 sameness = (len({x, y, z}) == 1) 

This allows you to use any number of variables. For instance:

 variables = {x, y, z, a, b, ...} sameness = (len(variables) == 1) 

Note. Creating a set means that each variable must be hashed and hashed values ​​must be saved, but all() with the generator expression is short-circuited and only tracks two values ​​at a time. Therefore, in addition to its readability, the expression of the generator is more efficient.

+1
source

In my case, the value will be either 1 or 2 , but I only need to know if they are all the same

Is it possible to check if 1 is in each: x, y and z? Even better, is there a more concise way of checking simply if x, y and z are the same value?

Sure:

 x == y == z 

which is equivalent

 (x == y) and (y == z) 

If you have an arbitrary (nonzero) number of values ​​to compare:

 all(values[0] == v for v in values[1:]) 
+1
source

All Articles