Tip 21 Make Your Code Compact with Conditional Expressions

Pythonic Programming — by Dmitry Zinoviev (30 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Embrace Comprehensions | TOC | Find the “Missing” Switch 👉

★★2.7, 3.4+ The conditional expression x if cond else y with the conditional operator if-else is a replacement of the conditional statement. The value of the expression is x if the condition cond is true and y, otherwise. Note that the conditional statement does not have a value as such because it is not an expression. Only expressions have values. The following two code fragments are equivalent:

​ ​# Conditional statement​
​ ​if​ cond:
​ value = x
​ ​else​:
​ value = y

​ ​# Conditional expression​
​ value = x ​if​ cond ​else​ y

On the bright side, the conditional expression is much more compact (a one-liner). On the not-so-bright side, the conditional statement allows more than one line in each branch, if necessary. In a sense, conditional expressions to conditional statements are what lambda functions are to “real” functions (Tip 60, Savvy Anonymous Functions).

The conditional operator shines when you must use one expression — for example, in a list comprehension. The following list comprehension converts the words that start with a capital letter to the uppercase (assuming that they have at least one character):

​ WORDS = ​'Mary had a little Lamb'​.split()
​ [(word.upper() ​if​ word ​and​ word[0].isupper() ​else​ word)…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.