Girrafish
Girrafish

Reputation: 2482

Pythonic way - Ternary vs or

I'm really just wondering, when it comes to this type of situation, what is the pythonic way of doing it? Using an if else ternary or an or:

true_list = []
for x, y in a_list: # x, y could be any truthy or falsy value
  true_list.append(x or y)
  true_list.append(x if x else y)

Edit: I updated the question to ignore the semantics, I was mostly wondering about which expression is more pythonic.

Upvotes: 1

Views: 990

Answers (2)

chepner
chepner

Reputation: 530950

This is the situation for which the conditional operator was introduced; use it.

string += x if x else y  # Or ... if x is not None ... if the distinction is necessary

In general, use or when you only care about the truthiness of the expression, without caring about the "actual" value whose truthiness is under consideration.

The conditional expression was introduced because many people tried to write code like

<condition> and x or y

but this is subtlely wrong: the intention is for the expression to equal x if the condition is true, but it really only equals x if both the condition and x are true.

Upvotes: 3

nmq
nmq

Reputation: 3154

In the case where both x and y can be None you could do the more verbose:

>>> string = ""
>>> x, y = (None, None)
>>> string += x if x else y if y else '' # Fallback to empty string
>>> string
''

Upvotes: 2

Related Questions