Thursday, November 1, 2012

Python Ternary Operator

I was checking webmasters and noticed a search for python lambda if else that lead to here. I figured if Google was already pointing in this direction, I may as well make a post since I already know how to use an if/else in Python.

The first thing to note is that you use a ternary operator. Ternary operators are relatively recent to Python and most people I know don't seem to like ternary operators. The reason we need to use a ternary operator is because a lambda function must return a value and ternary operators always return a value. Their very purpose is to return a value based on a condition for things like variable assignments or returns on a function. The syntax for a ternary operation in Python is as follows (with variable assignment).

x = valueIfTrue if someCondition else valueIfFalse

So you can have something along the lines of this.

x = 1
print "It is one" if x == 1 else "It is not one"
# It is one

It can also be used as a single argument for a function. Due to this being a one-line statement that always returns a value, it can be used to preform a simple if/else within a lambda function.

even = lambda x: False if x % 2 else True

Now like magic, we created a lambda function for even numbers. This can be used for filtering or mapping a list, however using list comprehension is faster and does not require creating a lambda function, not to mention with a little alteration you can have a generator expression.

So there's a quick and dirty introduction to ternary operators in Python and how to evaluate an if/else in a lambda function.

Tag Cloud

.NET (1) A+ (2) addon (6) Android (3) anonymous functions (5) application (10) arduino (1) artificial intelligence (2) bash (4) c (7) camera (1) certifications (4) cobol (1) comptia (4) computing (2) css (2) customize (16) encryption (2) error (19) exploit (17) ftp (3) funny (2) gadget (2) games (2) Gtk (1) GUI (5) hardware (6) haskell (15) help (8) HTML (6) irc (2) java (5) javascript (21) Linux (19) Mac (4) malware (2) math (8) network (9) objects (2) OCaml (1) perl (4) php (9) plugin (7) programming (42) python (24) radio (1) regex (3) security (25) sound (1) speakers (1) ssh (3) story (1) Techs from the Crypt (2) telnet (2) tools (14) troubleshooting (5) Ubuntu (4) Unix (4) virtualization (1) web design (14) Windows (7) wx (2)