4 ms·
People raging over the ternary operation in Python should learn to use: x = {True: 5, False: 4}[condition()] , or if you don't want to evaluate the values:
by empiko 5y ago
People raging over the ternary operation in Python should learn to use:
x = {True: 5, False: 4}[condition()]
, or if you don't want to evaluate the values:
x = {True: lambda: 5, False: lambda: 4}[condition()]()
- deleted 5y ago[deleted]
- jusssi 5y agoThis pattern also nicely expands when you need to select from more than 2 values. And it lets you keep the mapping as a data instead of turning it into logic. {"a": 1, "b": 2}.get(selector(), default_value) for the else-case.
- vsnf 5y agoThis is perhaps one of the most obscure ways to do ternaries I could have thought of, and while it really is quite clever, I think I'd be pretty annoyed if I encountered it in the wild.
- boomlinde 5y agox = (4, 5)[condition()] for a bonus "what am I looking at again?"
- Sinidir 5y agoBrilliant.