Is it possible to use 'else' in a python list comprehension?

Posted by Josh on Stack Overflow See other posts from Stack Overflow or by Josh
Published on 2010-06-01T16:57:10Z Indexed on 2010/06/01 17:03 UTC
Read the original article Hit count: 245

Filed under:
|

Here is the code I was trying to turn into a list comprehension:

table = ''
for index in xrange(256):
    if index in ords_to_keep:
        table += chr(index)
    else:
        table += replace_with

Is there a way to add the else statement to this comprehension?

table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)

Also, would I be right in concluding that a list comprehension is the most efficient way to do this?

© Stack Overflow or respective owner

Related posts about python

Related posts about list-comprehension