Last Updated: September 09, 2019
·
856
· eugeny

In-place value conversion in Python

Tired of long ternary operators?

v = 'yes' if x == 1 else 'no' if x == 0 else 'maybe'

Use a dict for in-place conversion!

v =  {1: 'yes', 0: 'no', None: 'maybe!'}[x]

2 Responses
Add your response

v = (x == 1) and 'yes' or (x == 0) and 'no' or 'maybe'

over 1 year ago ·

But behavior will be a bit different. None in dict won't catch values other than 1 or 0. :(

Anyway good sample. Thanks.

over 1 year ago ·