Python Ternary Operator Without else

PythonTernary

Python Problem Overview


Is it possible to do this on one line in Python?

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

I have tried the ternary operator:

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

but my IDE (MyEclipse) didn't like it, without an else.

Python Solutions


Solution 1 - Python

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']

Solution 2 - Python

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.

Solution 3 - Python

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

Otherwise, no. Why the need to put it on one line?

Note that the "ternary operator" is an operator. Like any operator, it must return something, so how can you have a ternary operator without the else clause? What is it supposed to return if the condition isn't true-like?

Solution 4 - Python

You are basically asking for do_thing() if <condition> else pass construct (which will throw SyntaxError, if ran). As I have discovered during research for (somewhat) similar question do_thing() if condition else None is as close as you can get (which is just another way to do <condition> and do_thing()). So, to summarize this idea and other answers, here are your options:

  • if <condition>: myList.append('myString') — seems to be the least 'hacky' (and thus preferred) way
  • <condition> and myList.append('myString')
  • myList.append('myString') if <condition> else None

Solution 5 - Python

myList.extend(['myString'] if condition else []) would also work, though it's more work than the other solutions.

Solution 6 - Python

You can do something like below. Note that None is never at any point appended to myList.

myList.append('myString') if <condition> else None

Also, Python should accept the one-liner below.

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

Solution 7 - Python

i’d just do this if i wanna add optional elements to a list based on a condition.

nums = [
        1,
        2,
        3 if <condition> else None,
        4,
       ]

# nums now contains values of `None`, so we delete all occurrences of `None`
nums.remove(None)

this just replaces the value with None if the condition is not met and then later, it just redefines the list without the None Values. this way they preserve their index if the condition is met

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJCBView Question on Stackoverflow
Solution 1 - PythonClaudiuView Answer on Stackoverflow
Solution 2 - PythonEmmett ButlerView Answer on Stackoverflow
Solution 3 - PythonmgilsonView Answer on Stackoverflow
Solution 4 - Pythonuser8554766View Answer on Stackoverflow
Solution 5 - PythonJake BiesingerView Answer on Stackoverflow
Solution 6 - PythonZachary ChiodiniView Answer on Stackoverflow
Solution 7 - Pythonpoison_pwnView Answer on Stackoverflow