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:
Here's an example:
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:
In this example, if the number is less than 4, it doubles odd numbers; otherwise, it multiplies them by 3.