Open In App

How to handle a Python Exception in a List Comprehension?

Improve
Improve
Like Article
Like
Save
Share
Report

An exception is something that interrupts the flow of the program. These exceptions stop the process running and sends out an error message. Exceptions can be simply viewed as an object that represents an error. There are predefined exceptions and user-defined exceptions in Python. In this article, we will discuss how to handle Python exception in a list comprehension but let’s first learn what is list comprehension.

List comprehension in Python

List comprehension is used to create new lists from the existing lists or any other iterable in Python. The elements in one iterable are iterated through, checked for some condition if required and if it satisfies the specified criteria it will be added to the new iterable. 

Syntax:

new_list=[variable_name  <for loop>  <if-condition>]

In Python, there are no special built-in methods to handle exceptions that occur in the list comprehensions. This article contains the code snippets that can be used for handling the exceptions that raise in list comprehensions.

Predefined exception handling

Let’s see some of the predefined exception handlings in list comprehension.

1) Handling ZeroDivisionError

Consider two lists (list1, list2) that contain integers. Now a new list (list3) is required to be formed by dividing the list1 elements by list2 elements. It can be formulated as given below.

list3 [i] = list1 [i] / list2 [i]

On diving the elements by 0, error raises. This exception should be caught and the error message should be displayed. This can be achieved by writing a utility function as given in the coding snippet below.

Python3




list1 = [2, 6, 41, 1, 58, 33, -7, 90]
list2 = [1, 3, 2, 0, 6, 3, 7, 0]
  
  
def util_func(a, b):
    try:
        return round(a/b, 3)
    except ZeroDivisionError as e:
        print("Division by zero not permitted!!!")
  
  
list3 = [util_func(x, y) for x, y in zip(list1, list2)]
  
print(list3)


Output:

Division by zero not permitted!!!
Division by zero not permitted!!!
[2.0, 2.0, 20.5, None, 9.667, 11.0, -1.0, None]

In this case, a custom error message is printed. 

2) Handling ValueError

Consider a list that contains integers, integers in string format, and also words put together. Now a new list is required to be formed by taking the numerals (which is in the string and int format) alone and squaring them up. But here the string values need to just skip and no error message is required to be printed.

Python3




li = ['10', '11', 7, 'abc', 'cats', 3, '5']
  
# helper function
def util_func(a):
    try:
        return int(a)*int(a)
    except ValueError:
        pass
  
  
# list comprehension
new_li = [util_func(x) for x in li]
  
print(new_li)


Output:

[100, 121, 49, None, None, 9, 25]

Since we just wanted to ignore the non-numeral values, we did not get any exception message and the None value is filled in the places where exception was raised.

User-defined exception handling

The user-defined exceptions can be anything like the value should be in a specified range or the value should be divisible by some number or anything else. For this, a class that inherits the built-in Exception class has to be constructed. Then the exception can be checked with the use of helper function. Consider the below examples.

Example 1: Consider a list of integers [2,43,56,-78,12,51,-29,17,-24]. The task is to pick out the integers that are divisible by 2 and form a new list. For the non-divisible numbers, the number should be printed with an error message.

Python3




# class for user-defined exception handling
class error(Exception):
    def __init__(self, a):
        self.msg = "The number "+str(a)+" is not divisible by 2!!"
  
# helper function
def util_func(a):
    try:
        if a % 2 != 0:
            raise error(a)
        return(a)
    except error as e:
        print(e.msg)
  
  
# input list
li = [2, 43, 56, -78, 12, 51, -29, 17, -24]
  
# list comprehension to choose numbers
# divisible by 2
new_li = [util_func(x) for x in li]
  
print("\nThe new list has :", new_li)


Output:

The number 43 is not divisible by 2!!
The number 51 is not divisible by 2!!
The number -29 is not divisible by 2!!
The number 17 is not divisible by 2!!

The new list has : [2, None, 56, -78, 12, None, None, None, -24]

Example 2: Form a new list from the existing one such that the selected values are between 10 and 20.

Python3




# class for user-defined exception handling
class error(Exception):
    def __init__(self, a):
        self.msg = "The number "+str(a)+" is not in range!!!"
  
# helper function
def util_func(a):
    try:
        if a < 10 or a > 20:
            raise error(a)
        return(a)
    except error as e:
        print(e.msg)
        return 0
  
  
# input list
li = [11, 16, 43, 89, 10, 14, 1, 43, 12, 21]
  
# list comprehension to choose numbers
# in range 10 to 20
new_li = [util_func(x) for x in li]
  
print("\nThe new list has :", new_li)


Output:

The number 43 is not in range!!!
The number 89 is not in range!!!
The number 1 is not in range!!!
The number 43 is not in range!!!
The number 21 is not in range!!!

The new list has : [11, 16, 0, 0, 10, 14, 0, 0, 12, 0]


Last Updated : 29 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads