In Python, list comprehensions provide a compact way to create new lists by iterating over an existing list and applying a transformation to each element. However, writing an if-else statement within a list comprehension can be tricky.
Consider the following example:
<code class="python">l = [22, 13, 45, 50, 98, 69, 43, 44, 1]</code>
Suppose you want to create a new list by adding 1 to numbers greater than or equal to 45, and 5 to numbers less than 45.
Attempting to write this as a list comprehension with an if-else statement like this:
<code class="python">[x+1 for x in l if x >= 45 else x+5]</code>
will result in a syntax error.
To perform an if-else operation within a list comprehension, you can use the ternary conditional operator:
<code class="python">[x+1 if x >= 45 else x+5 for x in l]</code>
This expression evaluates to:
<code class="python">[27, 18, 46, 51, 99, 70, 48, 49, 6]</code>
In this example, 'x 1' is executed for each x greater than or equal to 45, and 'x 5' is executed for each x less than 45.
The above is the detailed content of How do you use if-else statements within Python list comprehensions?. For more information, please follow other related articles on the PHP Chinese website!