Python Forum

Full Version: comparing multiple values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have several variables that at one point i expect them all to have the same value and need to test it:
   ...
   if a==b and b==c and c==d and d==e and e==f and f==g and g==h:
        print('they are all the same')
    else:
        print('it did not work')
is there a better way to test if they are all alike?  i can set it up so they are all in a list or tuple making up the whole sequence.  i'm thinking maybe sorting a list and comparing first to last.
First thing that comes to mind is doing it with a for loop.

But a nice thing to try would be putting all elements you want to check in a set and then checking its length, since there will be no duplicate items.
Doing it that way is also practical, because you can keep using/modifying the same set throughout the program, if it is a long running/repetitive task.
Yes, just use functional programming style:

functools.reduce(operator.eq, [a,b,c,d])
You can chain them:

>>> a, b, c, d = 1, 1, 1, 1
>>> a == b == c == d
True
>>>
But I like the @DeaD_EyE's answer more. I have to see this reduce and operator methods.
@DeaD_EyE's answer may well be the more elegant answer.  but is it the more pythonic one?  is it the better one?  now that you have seen them all, which would you code for this case?  are there any you would be upset with if you see them in someone else's code?  are there any you would be upset with if they are in contributions to one of your projects?
You can always put some comment to clarify what is doing. @DeaD_EyE's answer can be applied to a list with arbitrary length without getting ugly.