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)
Yes,
else
can be used in Python inside alist
comprehension with a Conditional Expression ("ternary operator"):Here, the parentheses "()" are just to emphasize the conditional expression, they are not necessarily required (Operator precedence).
Additionaly, several expressions can be nested, resulting in more
else
s and harder to read code:On a related note, a comprehension can also contain its own
if
condition(s) at the end:Conditions? Yes, multiple
if
s are possible, and actually multiplefor
s, too:(The single underscore
_
is a valid variable name (identifier) in Python, used here just to show it's not actually used. It has a special meaning in interactive mode)Using this for an additional conditional expression is possible, but of no real use:
Comprehensions can also be nested to create "multi-dimensional" lists ("arrays"):
Last but not least, a comprehension is not limited to creating a
list
, i.e.else
andif
can also be used the same way in aset
comprehension:and a
dictionary
comprehension:The same syntax is also used for Generator Expressions:
which can be used to create a
tuple
(there is no tuple comprehension).Further reading:
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.
Great answers, but just wanted to mention a gotcha that "pass" keyword will not work in the if/else part of the list-comprehension (as posted in the examples mentioned above).
This is tried and tested on python 3.4. Error is as below:
So, try to avoid pass-es in list comprehensions
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.The syntax
a if b else c
is a ternary operator in Python that evaluates toa
if the conditionb
is true - otherwise, it evaluates toc
. It can be used in comprehension statements:So for your example,
If you want an
else
you don't want to filter the list comprehension, you want it to iterate over every value. You can usetrue-value if cond else false-value
as the statement instead, and remove the filter from the end: