- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How to catch a 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.
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.
letters = [letter for letter in 'APPLE']
['A', 'P', 'P', 'L', 'E']
Exception Handling in List Comprehension
An exception is an unexpected error or event that occurs during the execution of 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 deflects 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 which can generate an error, you can utilize 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 Built-in Exceptions
Let's look at some of the built-in exception handling in list comprehension.
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.
ZeroDivisionError is thrown when a finite number is divided by a zero. It is a built-in exception which 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.
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)
Division by zero not allowed [None, 23.0, 17.0, 15.0, 14.0]
ValueError is an exception in Python which is raised when the argument passed to a function is of the correct data type but of invalid value. For example, passing negative integers to a function trying to find a square root of a number.
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]
Other built-in exceptions can also be handled in the same way using the try-except block.
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.
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 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]
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)
Output 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]
- Related Articles
- How to catch KeyError Exception in Python?
- How to catch IOError Exception in Python?
- How to catch ArithmeticError Exception in Python?
- How to catch OverflowError Exception in Python?
- How to catch IndexError Exception in Python?
- How to catch NameError Exception in Python?
- How to catch EOFError Exception in Python?
- How to catch SyntaxError Exception in Python?
- How to catch IndentationError Exception in python?
- How to catch TypeError Exception in Python?
- How to catch EnvironmentError Exception in Python?
- How to catch LookupError Exception in Python?
- How to catch ZeroDivisionError Exception in Python?
- How to catch FloatingPointError Exception in Python?
- How to catch StopIteration Exception in Python?