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))

Leave a Comment