How to Use if-elif-else in Python List Comprehensions
List comprehensions in Python provide a concise way to create new lists based on existing iterables. While list comprehensions are often used with a single if
condition, it's also possible to incorporate if-elif-else
logic for more complex filtering and transformations.
This guide explains how to use if-elif-else
(and simple if-else
) within list comprehensions, balancing brevity with code readability.
List Comprehensions with if-else
The basic structure for using an if-else
statement in a list comprehension is:
new_list = [expression_if_true if condition else expression_if_false for item in iterable]
expression_if_true
: The value to include in thenew_list
ifcondition
is true.condition
: The boolean expression to evaluate for eachitem
.expression_if_false
: The value to include in thenew_list
ifcondition
is false.item
: The current element being processed from theiterable
.iterable
: The original list (or other iterable) you're processing.
Example:
a_list = [1, 2, 2, None, 1, None]
new_list = [0 if item is None else item for item in a_list]
print(new_list) # Output: [1, 2, 2, 0, 1, 0]
In this case, the new_list
is created with:
- Existing items from
a_list
, if the item is not equal toNone
0
if the item isNone
List Comprehensions with if-elif-else
(Nested Ternary Operators)
To incorporate if-elif-else
logic, you nest ternary operators (condition ? value_if_true : value_if_false
). This gets complex quickly, so use it judiciously.
a_list = [1, 2, 2, 5, 1, 9]
new_list = [
'a' if item == 1
else 'b' if item == 2
else 'c'
for item in a_list
]
print(new_list) # Output: ['a', 'b', 'b', 'c', 'a', 'c']
The expression is evaluated from left to right. It checks if the item is equal to 1
and returns "a"
if it is. Otherwise, it evaluates the next condition.
The structure is:
new_list = [
expression1 if condition1
else expression2 if condition2
else expression3
for item in iterable
]
Another example:
a_list = [1, 2, 2, None, 1, None]
new_list = [
0 if item is None
else item if item % 2 == 0 else item + 11
for item in a_list
]
print(new_list) # Output: [12, 2, 2, 0, 12, 0]
Readability and Alternatives
Nested ternary operators within list comprehensions can quickly become hard to read. If you have more than one or two elif
conditions, or if the logic is complex, it's almost always better to use a standard for
loop with if
/elif
/else
statements for clarity.
Here's the equivalent of the previous example using a standard loop:
a_list = [1, 2, 2, None, 1, None]
new_list = []
for item in a_list:
if item is None:
new_list.append(0)
elif item % 2 == 0:
new_list.append(item)
else:
new_list.append(item + 11)
print(new_list) # Output: [12, 2, 2, 0, 12, 0]
This for
loop version is significantly more readable than the nested ternary version. Prioritize readability, especially for complex logic.