Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Ternary Operator Without else

Tags:

python

ternary

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.

like image 420
JCB Avatar asked Aug 30 '12 14:08

JCB


People also ask

Can we use ternary operator without else condition?

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.

Can I use if in Python without else?

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.

Is there any ternary operator in Python?

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.

What is an alternative of ternary operator in Python?

Another way to implement ternary operation in Python is by using a tuple. This is a simple replacement for the if-else ternary operator.


1 Answers

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'] 
like image 91
Claudiu Avatar answered Sep 18 '22 17:09

Claudiu