How to Use "if-else" in a Python List Comp.?

Find out how to use a conditional expression in a Python list comprehension

Starting with Python 2.5+, you can use if-else (which is actually the ternary operator) in a Python list comprehension to add a conditional expression.

You can use the if-else clause in a list comprehension to transform the items (to one value or the other) in the new list that the comprehension generates.

Syntax

It has the following syntax:

# Python 2.5+
[a if C else b for x in iterable]

In the conditional expression "a if C else b", C is evaluated first as it is the condition. If C is true, then a is evaluated and its value is returned; otherwise, b is evaluated and its value is returned.

This is equivalent to:

result = []

for x in iterable:
    if C:
        result.append(a)
    else:
        result.append(b)

Examples

For example, consider the following list comprehension where the string 'odd' or 'even' is added to a new list depending on whether the current number being iterated over is odd or even:

# Python 2.5+
nums = [1, 2, 3, 4]
result = ['even' if n % 2 == 0 else 'odd' for n in nums]
print(result) # ['odd', 'even', 'odd', 'even']

The if-else clause itself is not a part of the comprehension syntax, but is rather a language construct which can be used here to conditionally add one value or the other to the new list that's created by the list comprehension.

Please note that it is not possible to omit the else from the conditional expression, and using if-else is different from the if clause, which appears after the for clause(s).

Although, it's possible to use multiple if-else in a list comprehension, you should avoid it as it leads to hard-to-read code.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.