Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 share the same value. In my case, the value will either be 1 or 0, but I only need to know if they are all the same. Currently I'm using

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

Looking for the answer I've found:

if 1 in {x, y, z}: 

However, this operates as

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? Better yet, is there a more concise way of checking simply if x, y, and z are the same value?

(If it matters, I use Python 3.)

like image 623
Nevermore Avatar asked May 22 '16 16:05

Nevermore


People also ask

Can multiple variables have the same value?

Again, remember that there is absolutely no algebraic rule that states that two or more variables can not equal the same number. Each point that the graph passes through represents an (X,Y) coordinate that would make the equation true.

How do you know if three variables are equal?

To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.

How do you check if two variables are the same value in Python?

Use the == operator to test if two variables are equal.

How do you check for multiple equality in Python?

Python Code: x = 20 y = 20 z = 20 if x == y == z == 20: print("All variables have same value!") Sample Output: All variables have same value!


2 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 == 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: 
like image 158
Martijn Pieters Avatar answered Sep 24 '22 07:09

Martijn Pieters


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

sameness = (x == y == z) 

The parentheses are optional, but I find it improves readability

like image 34
Neapolitan Avatar answered Sep 21 '22 07:09

Neapolitan