Is it possible to use 'else' in a list comprehension? [duplicate]
The syntax a if b else c
is a ternary operator in Python that evaluates to a
if the condition b
is true - otherwise, it evaluates to c
. It can be used in comprehension statements:
>>> [a if a else 2 for a in [0,1,0,3]][2, 1, 2, 3]
So for your example,
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
If you want an else
you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value
as the statement instead, and remove the filter from the end:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
To use the else
in list comprehensions in python programming you can try out the below snippet. This would resolve your problem, the snippet is tested on python 2.7 and python 3.5.
obj = ["Even" if i%2==0 else "Odd" for i in range(10)]