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. Advertisements

  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. Advertisements

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. Peter Barth

    Mix lambda and list comprehension?

    Peter Barth, Jul 15, 2003, in forum: Python
    Replies:
    4
    Views:
    561
    Michele Simionato
    Jul 17, 2003
  2. George Henry

    Strange (?) list comprehension behavior

    George Henry, Jul 19, 2003, in forum: Python
    Replies:
    3
    Views:
    570
    Peter Hansen
    Jul 20, 2003
  3. jsaul

    'while' in list comprehension?

    jsaul, Oct 22, 2003, in forum: Python
    Replies:
    14
    Views:
    975
    Alex Martelli
    Nov 13, 2003
  4. Batista, Facundo

    RE: 'while' in list comprehension?

    Batista, Facundo, Oct 22, 2003, in forum: Python
    Replies:
    2
    Views:
    347
    Emile van Sebille
    Oct 22, 2003
  5. Batista, Facundo

    RE: 'while' in list comprehension?

    Batista, Facundo, Oct 22, 2003, in forum: Python
    Replies:
    1
    Views:
    433
    Francis Avila
    Oct 23, 2003
  6. Shane Geiger
    Replies:
    4
    Views:
    552
    bullockbefriending bard
    Mar 25, 2007
  7. Debajit Adhikary
    Replies:
    17
    Views:
    964
    Debajit Adhikary
    Oct 18, 2007
  8. Vedran Furac(
    Replies:
    4
    Views:
    541
    Marc 'BlackJack' Rintsch
    Dec 19, 2008
Loading...