Search code examples
pythonternary

Python Ternary Operator Without else


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.


Solution

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