List comprehension with if-else is used to create lists with conditional logic concisely. It allows elements to be filtered or modified while generating the new list.
Using if-else
This method applies an if-else condition directly inside the list comprehension. Each element is checked and a corresponding value is added to the new list.
a = [1, 2, 3, 4, 5]
res = ['Even' if n % 2 == 0 else 'Odd' for n in a]
print(res)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Explanation:
- Loop iterates through each number in a and n % 2 == 0 checks whether the number is even.
- 'Even' is added for even numbers, otherwise 'Odd'.
Using Only if Condition
This method adds elements only when the condition is true. Elements that do not satisfy the condition are skipped.
a = [1, 2, 3, 4, 5]
res = [n for n in a if n % 2 == 0]
print(res)
Output
[2, 4]
Explanation: loop iterates through each element in a and if n % 2 == 0 filters only even numbers.
Nested if-else
Nested if-else conditions are used to handle multiple conditions inside a single list comprehension.
a = [1, 2, 3, 4, 5]
res = ['Divisible by 2' if n % 2 == 0 else 'Divisible by 3' if n % 3 == 0
else 'Other'for n in a]
print(res)
Output
['Other', 'Divisible by 2', 'Divisible by 3', 'Divisible by 2', 'Other']
Explanation:
- Numbers are checked for divisibility by 2. If not divisible by 2, divisibility by 3 is checked.
- 'Other' is added when neither condition is true.