3

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?

Community
  • 1
  • 1
John
  • 1,724
  • 6
  • 25
  • 48

1 Answers1

8

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Be. Really. Careful. with the `or` short-circuits. Here there's no issue with it (because `someBoolValue` can only be True or False), but don't forget that some other objects like dict and list are considered as False when empty. – FunkySayu Jul 20 '15 at 12:19
  • @FunkySayu: yes, but that same value is going to be considered false in a conditional expression *anyway*. – Martijn Pieters Jul 20 '15 at 12:20
  • @John: yes, all objects in Python have a [truth value](https://docs.python.org/2/library/stdtypes.html#truth-value-testing), strings included. It doesn't matter what the value of the second expression is here. – Martijn Pieters Jul 20 '15 at 12:21
  • Also, note that `0` is falsey, so `num1 = 0 or 10` will result in `num1 == 10`, even though `0` is an integer value. As @FunkySayu said, you should be _very_ careful using `or` like this. – Frost Mar 03 '17 at 09:18
  • @Frost: note that the conditional expression in the question used the *exact same test*: `intvalue if intvalue else 10`. – Martijn Pieters Mar 03 '17 at 09:20
  • That's a good point. Thank you for pointing that out. So in that case, this will result in the same behavior. That makes me wonder whether that is the intended behavior of the code snippet or if `0` would be an acceptable value. That's another question though. – Frost Mar 03 '17 at 09:24