[Python] How to handle exceptions in a list comprehensions?

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    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 exception in the 3rd element.

    How can I handle this exception and continue execution of the list comprehension?

    The only way I can think of is to use a helper function:

    def spam(egg):
    try:
    return 1/egg
    except ZeroDivisionError:
    # handle division by zero error
    # leave empty for now
    pass


    But this looks a bit cumbersome to me.

    Is there a better way to do this in Python?

    Note: This is a simple example (see "for instance" above) that I contrived because my real example requires some context. I'm not interested in avoiding divide by zero errors but in handling exceptions in a list comprehension.

    Continue reading...

Compartilhe esta Página