Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a short way to check uniqueness of values without using 'if' and multiple 'and's?

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 ands. Is there a short way to tell Python that no 2 variable values should be the same.

like image 318
Bunny Davis Avatar asked Jun 22 '19 14:06

Bunny Davis


People also ask

How do you verify multiple variables?

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': ...

How compare multiple values in if condition?

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.

How do you check if multiple values are the same python?

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!


2 Answers

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.

like image 78
Ignatius Avatar answered Sep 22 '22 15:09

Ignatius


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 
like image 27
chepner Avatar answered Sep 18 '22 15:09

chepner