John
John

Reputation: 1852

One line if assignment in python

following this topic One line if-condition-assignment

Is there a way to shorten the suggested statement there:

num1 = (20 if intvalue else 10)

in case that the assigned value is the same one in the condition?

this is how it looks now:

num1 = (intvalue if intvalue else 10)

intvalue appears twice. Is there a way to use intvalue just once and get the same statement? something more elegant?

Upvotes: 3

Views: 4294

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121962

You can use or here:

num1 = intvalue or 10

or short-circuits; if the first expression is true, that value is returned, otherwise the outcome of the second value is returned.

Upvotes: 8

Related Questions