Python elif in list comprehension conditionals | Example code

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]



Python elif in list comprehension

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]


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.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.