0

I want to the return the value of the statement if it evaluates to true. For example,

if f():
   return f()
elif g():
   return g()

The function may return a list also. since empty list evaluates to false, is there a better way to do it. I don't want to store the value outside the scope of the if statement.

13
  • 3
    I don't understand what you're asking. What do you want to happen with an empty list? And why don't you want to store the value? Commented Apr 25, 2019 at 12:41
  • 4
    If you want to return f() if it is truthy (otherwise g()), then you could use return f() or g(). The information in your question is not very clear. Commented Apr 25, 2019 at 12:45
  • @khelwood This is true unless you don't want to return neither of f() or g() if they are not truthy (e.g. if neither of these things are true then I have to do some more work). Commented Apr 25, 2019 at 12:50
  • 1
    @khelwood your answer works good but the syntactically I was expecting something like jdehesa's answer. This is available in C++, I thought there would be a similar functionality in python. Commented Apr 25, 2019 at 12:59
  • @DanielRoseman I don't want to return an empty list that is why I have if checks Commented Apr 25, 2019 at 13:01

1 Answer 1

3

Currently you can only do:

out = f()
if out: return out
out = g()
if out: return out

But maybe what you are thinking of is something like the (controversial) assignment expressions coming up in Python 3.8. With this you will be able to do:

if out := f():
    return out
elif out := g():
    return out
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.