Handle Exceptions Inside List Comprehension

Paul Rubin http
Mon Oct 29 10:54:12 EDT 2007


beginner <zyzhu2000 at gmail.com> writes:
> [f(x) for x in xs]
> 
> I want to skip the point if f(x) raises an exception. How can I do
> that without totally removing the list comprehension?

def ff(xs):
  for x in xs:
     try: yield f(x)
     except: pass

[x for x in ff(xs)]   or alternatively

list(ff(xs))



More information about the Python-list mailing list