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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, you can do this:
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:
Demonstration: