Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to select first variable that evaluates to True

Tags:

python

I have some variables and I want to select the first one that evaluates to True, or else return a default value.

For instance I have a, b, and c. My existing code:

result = a if a else (b if b else (c if c else default))

Another approach I was considering:

result = ([v for v in (a, b, c) if v] + [default])[0]

But they both feel messy, so is there a more Pythonic way?

like image 625
hoju Avatar asked Nov 26 '09 12:11

hoju


2 Answers

Did you mean returning first value for what bool(value)==True? Then you can just rely on the fact that boolean operators return last evaluated argument:

result = a or b or c or default
like image 114
Denis Otkidach Avatar answered Sep 21 '22 00:09

Denis Otkidach


If one variable is not "defined", you can't access its name. So any reference to 'a' raises a NameError Exception.

In the other hand, if you have something like:

a = None
b = None
c = 3

you can do

default = 1
r = a or b or c or default
# r value is 3
like image 42
Juanjo Conti Avatar answered Sep 24 '22 00:09

Juanjo Conti