3 ms·
I prefer this Python syntax: x = condition() and 4 or 5
by hatmatrix 5y ago
I prefer this Python syntax:
x = condition() and 4 or 5
- klyrs 5y agoIf you know the first value is truthy, sure. x = condition() and [] or True is not equivalent to x = [] if condition() else True Now, I have seen a genuine application of `X and A or B` before. That occurs when you're checking a condition before, say, popping from a list -- but if the list is empty, you still want a default value.
- hatmatrix 5y agoCan you give me an example where the two return different values?
- klyrs 5y agoWhen condition() is truthy, the first evaluates to True and the second evaluates to [] Try it out. https://ideone.com/GciAs8 https://ideone.com/GciAs8
- hatmatrix 5y agoSo the problem is not in condition() but in the the other statement/expression. Similarly, True and False or 5 returns 5 rather than False.