Python list comprehension if without else | Example code

We can use list comprehension using if without else in Python.

num = [i for i in range(10) if i>=5]
print(num)

Python Example list comprehension if without else

Simple example code compares 2 iterable and prints the items which appear in both iterable.

a = [1, 2, 3, 4, 5]
b = [5, 2, 3]

res = [y for y in a if y in b]
print(res)

Output:

Python list comprehension if without else

Can an if statement in a list comprehension use an else?

Answer: Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension. The if/else is placed in front of them for a component of the list comprehension.

res = ["Yes" if num % 3 == 0 else "No" for num in range(1, 5)]

print(res)

Output: [‘No’, ‘No’, ‘Yes’, ‘No’]

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.