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_listifconditionis true.condition: The boolean expression to evaluate for eachitem.expression_if_false: The value to include in thenew_listifconditionis 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 0if 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
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.