I am writing some code and I need to compare some values. The point is that none of the variables should have the same value as another. For example:
a=1 b=2 c=3 if a != b and b != c and a != c: #do something
Now, it is easy to see that in a case of code with more variables, the if
statement becomes very long and full of and
s. Is there a short way to tell Python that no 2 variable values should be the same.
If you have the opposite case and you have multiple variables you need to check against one value, you can swap the left and right sides of the in operator. So instead of using or operators like this: >>> a, b, c = 3.1415, 'hello', 42 >>> if a == 'hello' or b == 'hello' or c == 'hello': ...
To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.
Use the equality operator to check if multiple variables are equal, e.g. if a == b == c: . The expression will compare the variables on the left-hand and right-hand sides of the equal signs and will return True if they are equal. Copied!
You can try making sets.
a, b, c = 1, 2, 3 if len({a,b,c}) == 3: # Do something
If your variables are kept as a list, it becomes even more simple:
a = [1,2,3,4,4] if len(set(a)) == len(a): # Do something
Here is the official documentation of python sets.
This works only for hashable objects such as integers, as given in the question. For non-hashable objects, see @chepner's more general solution.
This is definitely the way you should go for hashable objects, since it takes O(n) time for the number of objects n. The combinatorial method for non-hashable objects take O(n^2) time.
Assuming hashing is not an option, use itertools.combinations
and all
.
from itertools import combinations if all(x != y for x, y in combinations([a,b,c], 2)): # All values are unique
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With