Python Ternary Operator Without else

后端 未结 7 861
执笔经年
执笔经年 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:20

    You are basically asking for do_thing() if 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 and do_thing()). So, to summarize this idea and other answers, here are your options:

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

提交回复
热议问题