3 ms·
I'm personally a fan of conditional expressions, they're easy to read IMO as long as you're not nesting them. For instance, I find this unnecessarily difficult
by rectangletangle 11y ago
I'm personally a fan of conditional expressions, they're easy to read IMO as long as you're not nesting them.
For instance, I find this unnecessarily difficult to read.
>>> 0 if True else 1 if True else 2
0
But breaking it up like this keeps it reasonably concise, while retaining readability.
if True:
a = 0 if True else 1
else:
a = 2
print(a)
They can also be combined with comprehensions, which can be useful.
>>> import random
>>> ['a' if random.choice((True, False)) else 'b' for _ in range(6)]
['a', 'a', 'a', 'a', 'a', 'b']