Inline function with if/else: check returned value and append to list on condition, without calling function twice

3352 views python
-1

This one is hard to word. It comes from trying to understand inline functions.

This question is a spin-off of another question I asked: Evaluating input function inline, in order to append input or placeholder to a list

I want this code to work. The idea is, to evaluate the output of a function without calling it twice - and the choice should be appended to the list if it is equal to a set value:

import random

def returner():
    choices = ['cat', 'dog']
    return random.choice(choices)

list = []
list.append(returner() if returner() == 'dog' else 'got the cat in the bag')

The thing is, above I called the function twice. If it was a user input, it wouldn't be so great, to prompt the user twice. So I thought I could do:

list.append(x = returner() if x == 'dog' else 'got the cat in the bag')

Is it possible to do something like above?

answered question

This is a great example that one-liners are not always the best option.

2 Answers

5

If you know what you are comparing it against you could do

list = []
list.append("dog" if returner() == "dog" else "got cat in the bag")

otherwise you will have to do

list = []
r = returner()
list.append(r if r == 'dog' else 'got the cat in the bag')

in either case, you can actually make your code even more compact by changing these two lines

list = []
list.append("dog" if returner() == "dog" else "got cat in the bag")

into

list = ["dog" if returner() == "dog" else "got cat in the bag"]

posted this
8

You can defer the calling of returner() and put its result in a (1-element) list, that you can use:

import random

def returner():
    choices = ['cat', 'dog']
    return random.choice(choices)

l = [x if x == "dog" else 'got the cat in the bag' for x in [returner()] ]
print(l)

but I would be hesitent to do so - the approach of storing the (one) result of it beforehand is cleaner:

choi = returner()
l = [choi if choi == "dog" else 'got the cat in the bag' ]

posted this

Have an answer?

JD

Please login first before posting an answer.