Python list comprehension if elif else | Example code

You can’t use elif in list comprehension because it’s not part of the if-else short-expression syntax in Python.

Get the same logic with chaining:

if b1:
    a
elif b2:
    b
else:
    c

Becomes

a if b1 else b if b2 else c

Example list comprehension if elif else in Python

Simple example code.

[print('Hi') if num == 2 and num % 2 == 0 else print('Bye') if num % 2 == 0 else print(
'buzz') if num == 5 else print(num) for num in range(1, 6)]

Output:

Python list comprehension if elif else

Note: it is totally discouraged to use such unreadable list comprehensions in real-life projects!

Source: stackoverflow.com

Another Example

Python’s conditional expressions were designed exactly for this sort of use-case:

l = [1, 2, 3, 4, 5]
res = ['Y' if v == 1 else 'N' if v == 2 else 'Idle' for v in l]

print(res)

Output: [‘Y’, ‘N’, ‘Idle’, ‘Idle’, ‘Idle’]

Do comment if you have any doubts and suggestions on this Python list tutorial.

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.