Home > Article > Backend Development > How to Use if-Else Statements in Python List Comprehensions?
How to Use if-Else in Python List Comprehension
List comprehensions are a concise way to perform complex operations on lists. They allow for the creation of a new list based on the values of an existing list. However, sometimes you need to conditionally modify the elements in the new list based on a certain condition.
For example, consider the following scenario: You have a list of numbers called l, and you want to add 1 to numbers greater than or equal to 45, and add 5 to numbers less than 45.
The syntax to achieve this using list comprehension is as follows:
<code class="python">[x+1 if x >= 45 else x+5 for x in l]</code>
However, using the if-else statement in a list comprehension might result in a syntax error. To fix this, you need to use an extended syntax that involves encapsulating the if-else statement within square brackets:
<code class="python">[if x >= 45 then x+1 else x+5 for x in l]</code>
This syntax effectively replaces the if and else keywords with the keyword then.
In your specific case, the updated list comprehension would be:
<code class="python">[if x >= 45 then x+1 else x+5 for x in l]</code>
This will return the desired output:
<code class="python">[27, 18, 46, 51, 99, 70, 48, 49, 6]</code>
The above is the detailed content of How to Use if-Else Statements in Python List Comprehensions?. For more information, please follow other related articles on the PHP Chinese website!