Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the divide by zero exception in List Comprehensions while dividing 2 lists in Python

How to handle the divide by zero exception in List Comprehensions while dividing 2 lists in Python:

From below example:

from operator import truediv
result_list = map(truediv, [i for i in list1], [j for j in list2])

where the list2 can contain the 0 as value.

I want to handle the exception in the same line due to my code constrain. Please help me.

like image 528
user3270602 Avatar asked Aug 31 '15 09:08

user3270602


People also ask

How do you handle exceptions in list comprehension?

There is no built-in function in Python that lets you handle or ignore an exception, so it's not possible to handle all exceptions in a list comprehension because a list comprehension contains one or more expressions; only statements can catch/ignore/handle exceptions.

How do you catch a division by zero exception in Python?

You can't divide by zero! If you don't specify an exception type on the except line, it will cheerfully catch all exceptions. This is generally a bad idea in production code, since it means your program will blissfully ignore unexpected errors as well as ones which the except block is actually prepared to handle.

How is division by zero exception handled?

Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .


2 Answers

You cannot. try is a (compound) statement, a list-comprehension is an expression. In Python these are completely distinct things and you cannot have a statement inside an expression.

The thing you can do is using a wrapper function:

def add_handler(handler, exc, func):
    def wrapper(*args, **kwargs):

        try:
            return func(*args, **kwargs)
        except exc:
            return handler(*args, **kwargs)    # ???
    return wrapper

Then used as:

my_truediv = add_handler(print, ZeroDivisionError, truediv)

Note that this is very limited. You must return a value and insert it into the resulting list, you can't simply "skip it".

You should simply do:

from operator import truediv
result_list = []
for i, j in zip(list1, list2):
    try:
        result_list.append(i/j)
    except ZeroDivisionError:
        pass

Alternatively, if you simply want to skip those values you can just filter them out:

map(lambda x_y: truediv(*x_y), filter(lambda x_y: x_y[1] != 0, zip(list1, list2)))
like image 110
Bakuriu Avatar answered Oct 11 '22 12:10

Bakuriu


If you want to record the divisions by zero as NaN then you could use your own custom division function as follows:

import numpy as np

def divide(a, b):
    if b == 0:
        return np.nan
    else: 
        return a/b

list1 = [1, 2, 3]
list2 = [1, 0, 2]
result_list = map(divide, [i for i in list1], [j for j in list2])
like image 28
gtlambert Avatar answered Oct 11 '22 11:10

gtlambert