Python Ternary Operator Without else

Yes, you can do this:

<condition> and myList.append('myString')

If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and the element will be appended.

I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:

if <condition>: myList.append('myString')

Demonstration:

>>> myList = []
>>> False and myList.append('myString')
False
>>> myList
[]
>>> True and myList.append('myString')
>>> myList
['myString']

The reason the language doesn't allow you to use the syntax

variable = "something" if a_condition

without else is that, in the case where a_condition == False, variable is suddenly unknown. Maybe it could default to None, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.

Similarly, all returns must actually return, even if they are conditional returns. Eg:

return variable if a_condition

is not allowed, but

return variable if a_condition else None

is allowed, since the second example is guaranteed to explicitly return something.

Tags:

Python

Ternary