One line if statements in Python
Posted on: April 12, 2013 /
Every once in a while it is kind of nice to put a one-liner if statement in a Python program. I don’t use these very often as they can make the code harder to read. However I do think they have their place. Mainly I use these when I need set the value of a variable based on a condition. So lets say I start with a variable called dummy, and set it to None.
dummy = None
And I want to set dummy to something, but only if dummy is still none, so:
dummy = (something if dummy is None else dummy)
This is the same as writing:
if dummy is None:
dummy = something
dummy = dummy
The one line expression is a much simpler way to express this condition.