I have some a list comprehension in Python in which each iteration can throw an exception.
For instance, if I have:
eggs = (1,3,0,3,2)
[1/egg for egg in eggs]
I'll get a ZeroDivisionError
exception in the 3rd element.
How can I handle this exception and continue execution of the list comprehension?
The only way I can think of is to use a helper function:
def spam(egg):
try:
return 1/egg
except ZeroDivisionError:
# handle division by zero error
# leave empty for now
pass
But this looks a bit cumbersome to me.
Is there a better way to do this in Python?
Note: This is a simple example (see "for instance" above) that I contrived because my real example requires some context. I'm not interested in avoiding divide by zero errors but in handling exceptions in a list comprehension.
[1/egg except ZeroDivisionError: None for egg in (1,3,0,3,2)]
. But it's still in draft mode. My gut feeling is that it's not going to be accepted. Imho expressions can get too messy (checking multiple exceptions, having more complex combinations (multiple logical operators, complex comprehensions, etc)ndarray
with appropriate settings innp.seterr
. That would result in1/0 = nan
. But I realise that doesn't generalise to other situations where this need arises.