Handle Exceptions Inside List Comprehension

Discussion in 'Python' started by beginner, Oct 29, 2007.

  1. beginner

    beginner Guest

    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
    beginner, Oct 29, 2007
    #1
    1. Advertising

  2. beginner

    Paul Rubin Guest

    beginner <> 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))
    Paul Rubin, Oct 29, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Shane Geiger
    Replies:
    4
    Views:
    373
    bullockbefriending bard
    Mar 25, 2007
  2. Debajit Adhikary
    Replies:
    17
    Views:
    671
    Debajit Adhikary
    Oct 18, 2007
  3. Vedran Furac(
    Replies:
    4
    Views:
    316
    Marc 'BlackJack' Rintsch
    Dec 19, 2008
  4. Chris Angelico
    Replies:
    0
    Views:
    129
    Chris Angelico
    Nov 26, 2013
  5. Chris Angelico
    Replies:
    0
    Views:
    76
    Chris Angelico
    Nov 26, 2013
Loading...

Share This Page