
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch Python Exception in a List Comprehension
Before we understand how to catch a Python exception in a list comprehension, let us first learn what a list comprehension is.
Python List Comprehension
List comprehension is a statement that allows you to create a list and execute a for loop, all in a single sentence.
This also allows the lists to be created from other iterables like tuples, strings, arrays, lists, and so on. The syntax of list comprehension is given below -
List = [expression(element) for element in list if condition]
The Python list and list comprehension capability, which may be used inside a single line of code to generate substantial functionality, are two of the language's most distinguishing features.
There are no unique built-in methods in Python to handle exceptions that arise in list comprehensions. Hence, we can only do it using try/except blocks.
Example: Simple List Comprehension
In this example, we used a simple list comprehension to extract each character from the string APPLE and store it in a list -
letters = [letter for letter in 'APPLE'] print(letters)
We get the output as shown below -
['A', 'P', 'P', 'L', 'E']
Exception Handling in List Comprehension
An exception is an unexpected error or event that occurs during the execution of the program. Errors and Exceptions are often confused as the same; when an error occurs in a program, it stops executing, but when an exception is encountered, the program defers from its original course of execution. Hence, unlike errors, an exception can be handled. Therefore, you won't have a program crash.
Many times, there are both valid and invalid exceptions. Exceptions are useful for managing errors and exceptional conditions in a program in a variety of ways. When you think that you have a code that can generate an error, you can utilize the exception handling technique.
The raise exception statement can be used to raise an exception in your program. Raising an exception terminates current code execution and returns the exception until it is dealt with.
Handling ZeroDivisionError
ZeroDivisionError is thrown when a finite number is divided by zero. It is a built-in exception that is a part of the ArithmeticException class. This exception can be handled using a try-except block, where we change the output whenever this exception is raised. We can understand this better using an example.
Example
Since we are working with lists, let us try to divide the elements of one list by the elements of another list. These lists can also include zero.
In this example, we divided elements of one list by another using list comprehension. If division by zero occurs, it prints an error and stores None for that entry -
list_1 = [12, 23, 34, 45, 56] list_2 = [0, 1, 2, 3, 4] def func(a, b): try: return a/b except ZeroDivisionError: print("Division by zero not allowed") list_3 = [func(x, y) for x, y in zip(list_1, list_2)] print(list_3)
Following is the output of the above code -
Division by zero not allowed [None, 23.0, 17.0, 15.0, 14.0]
Handling ValueError
ValueError is an exception in Python which is raised when the argument passed to a function is of the correct data type but of an invalid value. For example, passing negative integers to a function trying to find the square root of a number.
Example
Consider a list that has integers, integers in string format, and words together. A new list must now be created by squaring the numerals (which are in string and int format). However, in this case, the string values must simply skip and no error notice must be issued.
list = ['10', '11', 7, 'abc', 'cats', 3, '5'] #helper function def func(a): try: return int(a)*int(a) except ValueError: pass # list comprehension new_list = [func(x) for x in list] print(new_list)
We received no exception message since we only wanted to ignore the non-numerical values, and the None value was filled in the areas where an exception was raised -
[100, 121, 49, None, None, 9, 25]
Handling Other Built-in Exceptions
Besides ZeroDivisionError and ValueError, Python provides many other built-in exceptions such as TypeError, IndexError, and KeyError. These can also be handled in a list comprehension using a helper function with a try-except block.
Example: Handling TypeError
Suppose we are trying to multiply each element of a list by 2, but some elements are not of a valid type for arithmetic operations (e.g., a list or dictionary). This would raise a TypeError, which we can handle using a try-except block -
data = [5, '3', [1, 2], 10, {'a': 1}] def safe_multiply(x): try: return x * 2 except TypeError: print(f"Cannot multiply value: {x}") return None result = [safe_multiply(item) for item in data] print(result)
The result produced is as shown below -
Cannot multiply value: {'a': 1} [10, '33', [1, 2, 1, 2], 20, None]
Handling User-defined Exceptions
The user-defined exceptions can be anything from the value being in a specific range to the value being divisible by some number. A class that inherits the built in Exception class must be created for this. The exception can then be tested using the helper function. Consider the examples below.
Example: Numbers Divisible by 2
Consider a list of integers. The goal is to pick out the integers that are divisible by two and form a new list. The number should be printed with an error message for the non-divisible numbers -
# creating 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 list = [12, 23, 34, 45, 56, 67] # list comprehension to choose numbers # divisible by 2 new_list = [util_func(x) for x in list] print("\nThe new list has :", new_list)
The output obtained is as follows -
The number 23 is not divisible by 2 The number 45 is not divisible by 2 The number 67 is not divisible by 2 The new list has : [12, None, 34, None, 56, None]
Example: Numbers Within a Specific Range
Create a new list from the existing one with values ranging between 10 and 20. We are raising an exception if the values fall outside the specified range, as shown in the example below.
# class for user-defined exception handling class error(Exception): def __init__(self, a): self.msg = "The num "+str(a)+" is out of 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 new_list = [12, 23, 34, 45, 56, 67] # list comprehension to choose the numbers # in range 10 to 20 new_li = [util_func(x) for x in new_list] print("\nThe new list are:", new_list)
The output for the program above is displayed as follows -
The num 23 is out of range!!! The num 34 is out of range!!! The num 45 is out of range!!! The num 56 is out of range!!! The num 67 is out of range!!! The new list are: [12, 23, 34, 45, 56, 67]