Python ‘if…else’ in a List Comprehension (Examples)

You can place an if...else statement into a list comprehension in Python.

For example:

["EVEN" if n % 2 == 0 else "ODD" for n in numbers]

Notice that the if...else statement in the above expression is not traditional if...else statement, though. Instead, it’s a ternary conditional operator, also known as the one-line if-else statement in Python.

Example

Given a list of numbers, let’s construct a list of strings that are odd/even based on what the corresponding number in the list of numbers is.

Here’s the code:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use a list comprehension to create a new list that includes
# "EVEN" for even numbers and "ODD" for odd numbers
even_or_odd = ["EVEN" if n % 2 == 0 else "ODD" for n in numbers]

print(even_or_odd)

# Output: ["ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN"]

In this example, the if..else clause in the list comprehension checks to see if the number n is even (that is, if n is divisible by 2 with no remainder). If it is, the string “EVEN” is included in the new list; otherwise, the string “ODD” is included.

The Traditional Approach

Let’s see the traditional for loop with an if...else statement approach for comparison:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Create an empty list to store the results
even_or_odd = []

# Use a for loop to iterate over the numbers
for n in numbers:
  # Use an if..else statement to determine if the number is even or odd
  if n % 2 == 0:
    even_or_odd.append("EVEN")
  else:
    even_or_odd.append("ODD")

print(even_or_odd)

# Output: ["ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN"]

Here’s a fun little illustration of converting the traditional approach to a list comprehension with an if…else statement:

One-Line If-Else Statements in Python

To add an if...else statement into a list comprehension in Python, you need to use a slightly modified version of an if...else statement, called the conditional operator.

The conditional operator in Python allows you to write conditional expressions in a shorter and more concise way. It is also known as the ternary operator because it takes three operands.

Here is the general syntax for using the conditional operator in Python:

x if condition else y

Here, x and y are the values that will be returned based on the evaluation of the condition. If the condition evaluates to True, x will be returned; otherwise, y will be returned.

Here is an example of using the conditional operator to return the maximum of two numbers:

# Define two numbers
x = 5
y = 10

# Use the conditional operator to return the maximum of x and y
max = x if x > y else y

# Print the maximum
print(max)

# Output: 10

The condition checks to see if x is greater than y. If it is, the value of x is returned; otherwise, it returns y.

The conditional operator can be useful whenever you want to write a conditional expression in a single line of code. It can make your code more readable and concise by avoiding multi-line if..else statements. Also, some argue it only makes the code shorter but less readable which is why some don’t use conditional operators at all.

To include an if...else statement into a list comprehension, you need to pass it as a conditional expression.

Example

Let’s take a look at another example of list comprehensions an if...else statements.

Here is an example of a for loop with an if...else statement that prints whether a number is odd or even in a list of numbers.

First, let’s start with the traditional approach:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for number in numbers:
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even

This for loop can be converted into a one-line list comprehension expression using a conditional operator if...else:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print([f"{number} is {'even' if number % 2 == 0 else 'odd'}" for number in numbers])

The output of this expression would be the same as the original for loop:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even

Should You Place If…Else Statements in List Comprehensions?

Whether or not you should use list comprehension expressions with conditional operators in your code depends on your personal preferences and the specific requirements of your project.

Some developers never use one-liner shorthand like list comprehensions or conditional operators.

List comprehensions can be a concise and elegant way to write certain types of for loops, but they can also make your code more difficult to read and understand if you are not familiar with the syntax.

If you are working on a small project with no collaborators, using list comprehension expressions (with if...else statements) can make your code more concise and easier to write.

However, if you are working on a larger project and you are collaborating with other people on a project, it may be more beneficial to use longer and more descriptive for loops that are easier for other people to read and understand.

Ultimately, the decision to use list comprehension in your code should be based on the specific needs of your project, the level of experience and familiarity of the people working on the project, and the trade-off between conciseness and readability.

My personal take: A list comprehension with an if...else statement looks messy and I’d probably not use such expression ever in my code.

Thanks for reading. Happy coding!

Read Also

Python One-Line If…Else Statements