Home  >  Article  >  Backend Development  >  How do you use if-else statements within Python list comprehensions?

How do you use if-else statements within Python list comprehensions?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 09:35:02482browse

How do you use if-else statements within Python list comprehensions?

If-Else in List Comprehensions

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn