![]() |
VOOZH | about |
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.
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.
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Explanation:
This method adds elements only when the condition is true. Elements that do not satisfy the condition are skipped.
[2, 4]
Explanation: loop iterates through each element in a and if n % 2 == 0 filters only even numbers.
Nested if-else conditions are used to handle multiple conditions inside a single list comprehension.
['Other', 'Divisible by 2', 'Divisible by 3', 'Divisible by 2', 'Other']
Explanation: