Search code examples
pythonany

any in python doesn't print content


I am playing with any, and found this:

def f():
    print(1)
    return True


def g():
    print(2)
    return False


if any(lambda x: x() for x in [g, f, f]):
    print(3)

I guess I would get

2
3

or

2
1
3

but only get

3

I don't know why.


Solution

  • The lambda is never actually called, so it itself is evaluated, and function objects are apparently truthy.

    >>> bool(lambda: False)
    True
    >>> bool(max)
    True
    >>> bool(f)
    True
    

    Simply remove the lambda part:

    if any(x() for x in [g, f, f]):
        print(3)
    

    Output:

    2
    1
    3