Search code examples
pythonconditional-expressions

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?


Solution

  • 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.