DEV Community

Cover image for Using ternaries for variable assignment in Python
ryanharris.dev
ryanharris.dev

Posted on

Using ternaries for variable assignment in Python

One of my favorite "tricks" as a programmer is to condense conditional logic (i.e. if/else blocks) into one line when assigning variables. The ternary operator makes this possible.

If you come from a JavaScript background like I do, you may have seen this done before with a question mark.

const isSuccess = data.response ? true : false
Enter fullscreen mode Exit fullscreen mode

Essentially, this means if data.response is defined we should assign isSuccess the value of true. Otherwise, we'll set it to false.

Recently, I used a ternary operation in Python for the first time. While it, ultimately, works the same way I found the slight difference between languages interesting.

To recreate the snippet above in Python, we could write:

is_success = True if data.response else False
Enter fullscreen mode Exit fullscreen mode

In this case, the right-side of the assignment leads with the "truthy" value, as opposed to the value we're checking. It's not a big difference, but worth noting the difference in API.

The ? operator has a special place in my heart because I've used it so much. However, Python's ternary operator syntax is probably easier to read for beginners.

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Not really the greatest example. As JS has the concept of truthiness and falsiness, then writing:

const isSuccess = data.response ? true : false
Enter fullscreen mode Exit fullscreen mode

is effectively the same as writing:

const isSuccess = data.response // actually making isSuccess kinda redundant
Enter fullscreen mode Exit fullscreen mode

unless you have a very solid reason for requiring a boolean (perhaps to include as part of a JSON request/response) - in which case you could just use:

const isSuccess = !!data.repsonse
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ryanharris profile image
ryanharris.dev

Fair point. For the purposes of demonstration I was "keeping it simple", but you're technically correct. Thanks for calling it out.

Personally, I'm not a huge fan of the !! because I think it is harder to grok than its alternatives.

Collapse
 
ryanharris profile image
ryanharris.dev

Didn't mean to suggest it was invented in JavaScript. My background is in JavaScript, so I was just drawing a parallel to my previous use of the conditional operator.