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
.
A ternary operation is called ternary because it takes 3 arguments, if it takes 2 it is a binary operation. It's an expression returning a value. If you omit the else you would have an undefined situation where the expression would not return a value. You can use an if statement.
You can write Python one line if without else statement by just avoiding an else. For it just writes the if statement in a single line! No needed tricks (like using the semicolon) that help you create one-liner statements.
Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.
Another way to implement ternary operation in Python is by using a tuple. This is a simple replacement for the if-else ternary operator.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With