Python List Comprehension Using If-Else
List comprehension with if-else
in Python is a concise way to apply conditional logic while creating a new list. It allows users to add elements based on specific conditions and even modify them before adding.
Using if-else
Inside List Comprehension
This is the simplest and most efficient way to apply conditional logic directly. This applies the if-else
condition directly in the list comprehension. Each number is checked for divisibility by 2, and either "Even" or "Odd" is added to the list.
a = [1, 2, 3, 4, 5]
# Add 'Even' for even numbers, otherwise 'Odd'
result = ['Even' if n % 2 == 0 else 'Odd' for n in a]
print(result)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Let's explore some other methods on how to use list comprehension using if-else
Using if
Condition Only (Without else
)
This method is used when elements are added only if the condition is met. Here, the if
condition filters out numbers that do not meet the condition. Only even numbers are added to the new list.
a = [1, 2, 3, 4, 5]
# Include only even numbers in the list
result = [n for n in a if n % 2 == 0]
print(result)
Output
[2, 4]
Nested if-else
in List Comprehension
Handle multiple conditions with nested logic. Using Nested if-else in List allows chaining of if-else
conditions. It categorizes each number based on whether it is divisible by 2, 3, or neither.
a = [1, 2, 3, 4, 5]
# Categorize numbers based on divisibility
result = ['Divisible by 2' if n % 2 == 0 else 'Divisible by 3' if n % 3 == 0 else 'Other' for n in a]
print(result)
Output
['Other', 'Divisible by 2', 'Divisible by 3', 'Divisible by 2', 'Other']