- Python ‘if…else’ in a List Comprehension (Examples)
- Example
- The Traditional Approach
- One-Line If-Else Statements in Python
- Example
- Should You Place If…Else Statements in List Comprehensions?
- List comprehension python if else elif
- # Table of Contents
- # Using elif statement in a List comprehension in Python
- # If you only have an if statement, specify it at the end
- # List comprehension with if-else statement in Python
- # Additional Resources
Python ‘if…else’ in a List Comprehension (Examples)
You can place an if. else statement into a list comprehension in Python.
["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.
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:
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")
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" is " 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!
List comprehension python if else elif
Last updated: Feb 23, 2023
Reading time · 6 min
# Table of Contents
# Using elif statement in a List comprehension in Python
To use an elif statement in a list comprehension:
- Use an if statement to check for a condition.
- Use an else statement to implement an elif clause.
- Use a second else statement to return a value if neither condition is met.
Copied!a_list = [1, 2, 2, 5, 1, 9] new_list = [ 'a' if item == 1 else 'b' if item == 2 else 'c' for item in a_list ] print(new_list) # 👉️ ['a', 'b', 'b', 'c', 'a', 'c']
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
We used an else statement to implement an elif clause in a list comprehension.
The if statement checks if the current item is equal to 1 and if the condition is met, a is returned.
The else statement returns another condition. The condition checks if the item is equal to 2 . If the condition is met, b is returned.
If neither condition is met, c is returned.
In pseudo-code, the syntax looks as follows.
Copied!new_list = [ return A if condition_is_met else return B if condition_is_met else return C for item in a_list ]
Notice that the if and else statements are at the beginning of the list comprehension.
Here is how we would implement the list comprehension from the example using a for loop.
Copied!a_list = [1, 2, 2, 5, 1, 9] new_list = [] for item in a_list: if item == 1: new_list.append('a') elif item == 2: new_list.append('b') else: new_list.append('c') # 👇️ ['a', 'b', 'b', 'c', 'a', 'c'] print(new_list)
The for loop from the code sample is equivalent to the list comprehension.
Here is another example of using an elif statement in a list comprehension.
Copied!a_list = [1, 2, 2, None, 1, None] new_list = [ 0 if item is None else item if item % 2 == 0 else item + 11 for item in a_list ] print(new_list) # 👉️ [12, 2, 2, 0, 12, 0]
The if statement checks if the current item is None and if the condition is met, 0 is returned.
The else statement implements another condition. The condition checks if the number divided by 2 has a remainder of 0 .
If the condition is met, the item is returned, otherwise, the item + 11 is returned.
The same approach can be used if you only need to implement an if-else statement in a list comprehension.
Copied!a_list = [1, 2, 2, None, 1, None] new_list = [ 0 if item is None else item for item in a_list ] print(new_list) # 👉️ [1, 2, 2, 0, 1, 0]
The if statement checks if the item is None. If the condition is met, 0 is returned, otherwise, the item is returned.
The syntax in pseudo-code looks as follows.
Copied!new_list = [ return A if condition_is_met else return B for item in list ]
Notice that the if and else statements are specified at the beginning of the list comprehension.
# If you only have an if statement, specify it at the end
If you only have an if statement in a list comprehension, make sure to specify it at the end.
Copied!a_list = [1, 2, 2, None, 1, None] new_list = [ item for item in a_list if item is not None ] print(new_list) # 👉️ [1, 2, 2, 1]
Implementing an if-elif-else statement in a list comprehension might make your code more difficult to read.
If that’s the case, simply use a for loop.
Copied!a_list = [1, 2, 2, None, 1, None] new_list = [] for item in a_list: if item is None: new_list.append(0) elif item % 2 == 0: new_list.append(item) else: new_list.append(item + 11) print(new_list) # 👉️ [12, 2, 2, 0, 12, 0]
The for loop approach is a bit more verbose but in my opinion, it is more readable and intuitive.
# List comprehension with if-else statement in Python
To use a list comprehension with if-else:
- Specify the if statement first in the list comprehension.
- Specify the else statement after the if .
- Iterate over a collection in the list comprehension.
Copied!a_list = [2, 4, 8, 13, 10] new_list = [ item if item > 8 else item + 10 for item in a_list ] print(new_list) # 👉️ [12, 14, 18, 13, 10]
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
The syntax for using if-else in a list comprehension is as follows.
Copied!new_list = [ return A if condition_is_met else return B for item in list ]
The syntax a if condition else b is called the ternary operator.
Copied!site = 'bobbyhadz.com' result = 'a' if len(site) > 1 else 'b' print(result) # 👉️ 'a'
The ternary operator returns the value to the left if the condition is met, otherwise, the value to the right is returned.
If you only have an if statement in your list comprehension, specify the condition at the end.
Copied!a_list = [2, 4, 8, 13, 10] new_list = [ item for item in a_list if item > 8 ] print(new_list) # 👉️ [13, 10]
However, you can’t have an if/else statement at the end of a list comprehension as it is invalid syntax.
Copied!a_list = [2, None, 4, None, 8] new_list = [ item if item is not None else 0 for item in a_list ] print(new_list) # 👉️ [2, 0, 4, 0, 8]
We used a list comprehension to iterate over the list.
The if statement checks if the current item is not None and if the condition is met, the item is returned.
Otherwise, the else statement returns 0 .
The list comprehension is equivalent to the following for loop.
Copied!a_list = [2, None, 4, None, 8] new_list = [] for item in a_list: if item is not None: new_list.append(item) else: new_list.append(0) print(new_list) # 👉️ [2, 0, 4, 0, 8]
You can also use an if with multiple else statements in a list comprehension to implement an elif condition.
Copied!a_list = [2, 4, 8, 4, 19] new_list = ['a' if item == 4 else 'b' if item == 8 else 'c' for item in a_list] print(new_list) # 👉️ ['c', 'a', 'b', 'a', 'c']
The if statement checks if the current item is equal to 4 and if the condition is met, the letter a is returned.
The else statement returns another condition.
The condition checks if the item is equal to 8 . If the condition is met, the letter b is returned, otherwise, the letter c is returned.
In pseudo-code, the syntax looks as follows.
Copied!new_list = [ return A if condition_is_met else return B if condition_is_met else return C for item in a_list ]
Here is how you’d implement the list comprehension from the previous example using a for loop.
Copied!a_list = [2, 4, 8, 4, 19] new_list = [] for item in a_list: if item == 4: new_list.append('a') elif item == 8: new_list.append('b') else: new_list.append('c') print(new_list) # 👉️ ['c', 'a', 'b', 'a', 'c']
We check if the item is equal to 4 and append a to a new list if the condition is met.
Otherwise, the elif statement checks if the current item is equal to 8 . If the condition is met, we append b to the new list.
If the conditions aren’t met, the else statement runs and we append c to the list.
Checking for too many conditions in list comprehensions might get more complicated than necessary.
In these cases, you can use a simple for loop for readability purposes.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.