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


#1

Question

When using a list comprehension with an if, is it possible to have an else clause?

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 the for component of the list comprehension.

divbythree = [  "Yes" if number % 3 == 0 else "No" for number in range(1,20)]
print(divbythree)