3

I want to realize something like use lambda to call a function which has an output of None or list and if it is a list, then get the first value.

lambda x: func(x,args)[0] if func(x,args) is not None else None

However, in this function it seems to need to call the function twice to find out whether it is None. Of course I can just write the code using try or conditional statements:

def function(x):
    try: 
        return func(x,args)[0]
    except (IndexError,TypeError):
        return None

or just change the output of func. But I am still curious about if there are some methods to call the function only once with lambda.

3
  • At the very least only catch the IndexError and TypeError exceptions that your code can throw, not everything else (including memory errors and keyboard interrupts). Commented Jul 11, 2017 at 12:46
  • Why not list = func(x,args); lambda x: list[0] if list else None Commented Jul 11, 2017 at 12:49
  • 2
    @yinnonsanders No, because then it takes 2 lines, not one. Commented Jul 11, 2017 at 12:51

1 Answer 1

14

This'll do:

lambda x: (func(x, args) or [None])[0]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.