Hi, I'm Chris

This blog is about programming, linux and other stuff.
Please don’t hesitate to contact me if you have any questions or suggestions for improvements!

Ternary operator in Python and R

If you know c or java, you are probably used to the neat ternary operator which allows you to do stuff like this:

foo = (condition) ? "true" : "false";

Which results in foo being set to “true” if condition is true and to “false” otherwise. This is basically just syntactic sugar for this expression:

if (condition):
    foo = "true";
    foo = "false";

Fortunately, this is also possible in my favored programming language, Python (and also in R, which I have to use quiet often).

This is the way to go in Python:

foo = "true" if (condition) else "false"

#this can be chained
foo = "true I" if (condition I) else "true II" if (condition II) else "false"

.. and this is how it’s done in R:

foo = if(condition) "true" else "false"

#this can be chained, too
foo = if(condition I) "true I" if(condition II) "true II" else "false"

Now you know how to use the ternary operator in Python and R but you should use it with care since the excessive use of the ternary operator can lead to unreadable code. You have been warned…