If/Else in a List Comprehension
Better Stack Team
Updated on June 19, 2024
You can use if/else statements in a list comprehension to conditionally include elements in the resulting list. The syntax for this is:
[expression_if_true if condition else expression_if_false for item in iterable]
Here's an example:
# List comprehension with if/else
numbers = [1, 2, 3, 4, 5]
new_numbers = [x if x % 2 == 0 else x * 2 for x in numbers]
print(new_numbers) # Output: [2, 2, 6, 4, 10]
In this example, the list comprehension doubles each odd number and leaves even numbers unchanged.
You can also use nested if/else statements for more complex conditions:
# List comprehension with nested if/else
numbers = [1, 2, 3, 4, 5]
new_numbers = [x if x % 2 == 0 else x * 2 if x < 4 else x * 3 for x in numbers]
print(new_numbers) # Output: [2, 2, 6, 12, 15]
In this example, if the number is less than 4, it doubles odd numbers; otherwise, it multiplies them by 3.