I want to apply a function in a list comprehension that does not "work" for certain values.
A simple example would be [1/x for x in [-2, -1, 0, 1, 2]]
.
I would like to write something that skips the 0
and returns the following list: [-0.5, -1.0, 1.0, 0.5]
.
My best shot so far was wrapping the division in a try
statement:
def try_div(x):
try:
return 1/x
except ZeroDivisionError:
pass
result_with_none = [try_div(x) for x in [-2, -1, 0, 1, 2]]
result = [x for x in result_with_none if x is not None]
This seems a bit inconvenient. Can I rewrite try_div
in a way that makes the list comprehension skip the 0
element?
Remark: In this simple example, I could of course write [try_div for x in [-2, -1, 0, 1, 2] if x != 0]
. This is not practicable in my actual use case, because it is not easy to check a priori which values will raise an exception.
Remark 2: In contrast to this question, I am fine with explicitly handling exceptions in a function (like try_div
). My question is mostly about how I could combine the last two steps (result_with_none = ...
and result = ...
) into one.