Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if all N variables are different

I want to make a condition where all selected variables are not equal. My solution so far is to compare every pair which doesn't scale well:

if A!=B and A!=C and B!=C:

I want to do the same check for multiple variables, say five or more, and it gets quite confusing with that many. What can I do to make it simpler?

like image 718
Ben.Sw Avatar asked Jul 19 '15 19:07

Ben.Sw


1 Answers

Create a set and check whether the number of elements in the set is the same as the number of variables in the list that you passed into it:

>>> variables = [a, b, c, d, e]
>>> if len(set(variables)) == len(variables):
...     print("All variables are different")

A set doesn't have duplicate elements so if you create a set and it has the same number of elements as the number of elements in the original list then you know all elements are different from each other.

like image 96
Simeon Visser Avatar answered Sep 19 '22 15:09

Simeon Visser