List comprehension with if-else statements is a powerful feature in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to use if-else statements in list comprehensions.
Example 1:
numbers = [1, 2, 3, 4, 5] even_or_odd = ['even' if num % 2 == 0 else 'odd' for num in numbers] print(even_or_odd)
Output: [‘odd’, ‘even’, ‘odd’, ‘even’, ‘odd’]
Example 2:
fruits = ['apple', 'banana', 'orange', 'kiwi'] long_short = ['long' if len(fruit) > 5 else 'short' for fruit in fruits] print(long_short)
Output: [‘short’, ‘short’, ‘long’, ‘short’]