views:

323

answers:

3

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)
+5  A: 

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))
Michael Mrozek
+16  A: 

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))
Amber
Note that this only works in Python 2.5 and later.
Kevin Horn
+1  A: 

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

Maybe. List comprehensions are not inherently computationally efficient. It is still running in linear time.

From my personal experience: I have significantly reduced computation time when dealing with large data sets by replacing list comprehensions (specifically nested ones) with for-loop/list-appending type structures you have above. In this application I doubt you will notice a difference.

orangeoctopus
woops, i meant to ask about the join method vs. += on a string.
Josh
Interesting. This (http://wiki.python.org/moin/PythonSpeed#Takeadvantageofinterpreteroptimizations) says otherwise.
KennyTM
@Josh: in older version of Python, the join() method is vastly superior. Newer versions of the interpreter attempt to optimize the += method, but I'm not sure how well this works. I almost always just use the join() method.
Kevin Horn