Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Handle Exceptions Inside List Comprehension

Reply
Thread Tools

Handle Exceptions Inside List Comprehension

 
 
beginner
Guest
Posts: n/a
 
      10-29-2007
Hi All,

I am wondering if there is any way to handle exceptions inside list
comprehension. For example,

[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?

Thanks,
Geoffrey

 
Reply With Quote
 
 
 
 
Paul Rubin
Guest
Posts: n/a
 
      10-29-2007
beginner <(E-Mail Removed)> 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))
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
List comprehension in if clause of another list comprehension Vedran Furac( Python 4 12-19-2008 01:35 PM
Appending a list's elements to another list using a list comprehension Debajit Adhikary Python 17 10-18-2007 06:45 PM
List comprehension returning subclassed list type? Shane Geiger Python 4 03-25-2007 09:34 AM
Checked exceptions vs unchecked exceptions Ahmed Moustafa Java 5 07-14-2004 01:46 PM
Custom exceptions -- inherit from exceptions.Exception? Paul Miller Python 3 11-12-2003 09:24 AM



Advertisments