There’s no direct use “elif” construct ist comprehension conditionals, but it can be simulated with nested if/else statements.
Common if-else syntax
['Yes' if v == 1 else 'No' for v in l]
The ternary form of the if/else operator doesn’t have an ‘elif’ built-in, but you can simulate it in the ‘else’ condition:
['Yes' if v == 1 else 'No' if v == 2 else '0' for v in l]
Python example elif in the list comprehension
Simple example code use list comprehension is you are going to create another list from the original.
l = [1, 2, 3, 4, 5]
res = ['Yes' if v == 1 else 'No' if v == 2 else '0' for v in l]
print(res)
Output:
Another Example code
Creating product reviews that take values from 1 to 5 and create a list with three categories:
- Good >= greater or equal to 4
- Neutral = if the review is 3
- Negative < if the review is less than 3
x = [5, 2, 1, 4, 5, 2]
res = ["Good" if i >= 4 else "Neutral" if i == 3 else "Bad" for i in x]
print(res)
Output: [‘Good’, ‘Bad’, ‘Bad’, ‘Good’, ‘Good’, ‘Bad’]
Do comment if you have any doubts and suggestions on this Python List topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.