Python Ternary Operator Without else

后端 未结 7 859
执笔经年
执笔经年 2020-11-29 00:36

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

if :
    myList.append(\'myString\')

I have tried the ternary operator:

7条回答
  •  甜味超标
    2020-11-29 01:10

    Yes, you can do this:

     and myList.append('myString')
    

    If is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If 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 : myList.append('myString')
    

    Demonstration:

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

提交回复
热议问题