Try Except In List Comprehension

Source URL: https://stackoverflow.com/questions/1528237/how-to-handle-exceptions-in-a-list-comprehensions

Language: python

Created on: 2021-02-02 08:13:45

# Python List Comprehension Error Handling:
# The correct responses to the question "how to handle exceptions in a list 
# comprehension" are all expressing part of all of this truth: 1) literally, 
# i.e. lexically IN the comprehension itself, you can't; 2) practically, you 
# delegate the job to a function or check for error prone values when that's 
# feasible.
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 exc...
content_copy