Python: What is the simples way to compare two numbers (in tuple) returned by a function?

Viewed 56

Consider a function that returns two numbers:

def func():
    # ....
    return a,b

What is the simplest way to apply the compare operator == to the result of the function?

I've tried with lambda but I'm looking for something simple:-

q = lambda x, y: x == y
[q(*func()) for i in range(16)]
2 Answers

The shortest way I can think of is to check

len(set(func())) == 1

(works without caveats because you said they were two numbers, so hashable)

But I would personally just assign the result of the function to a variable and then do it the normal way.

Edit: ohh, now I understand your lambda; it already exists as operator.eq:

from operator import eq

eq(*func())

Is rather neater.

If you can modify func() then you can add a third return value to it that would indicate if the first two return values are equal,

from random import randint

def fun():
    a = randint(0,5)
    b = randint(0,5)
    return a, b, a == b

res = [fun()[2] for i in range(10)]

If you can't modify func() then you can also use a decorator, though it is not really simpler, maybe just more robust and clear than the lambda:

from random import randint

def elem_equal(func):
    def wrapper():
        a,b = func()
        return a == b
    return wrapper

@elem_equal
def fun():
    a = randint(0,5)
    b = randint(0,5)
    return a, b

res = [fun() for i in range(10)]

The decorator elem_equal calls the target function func() and returns comparison of its return values.

Related