exception in list comprehension in python

We can use the try-except-else block inside the list comprehension to handle exceptions. Here is an example:

main.py
my_list = [1, 2, 3, 4, 0, 'a', 5, 6]

new_list = [10 / i if isinstance(i, int) and i != 0 else None for i in my_list]

print(new_list)
135 chars
6 lines

Output:

main.py
[10.0, 5.0, 3.3333333333333335, 2.5, None, None, 2.0, 1.6666666666666667]
74 chars
2 lines

In the above code, we use the isinstance() function to check if the element is an integer and not zero. If it is a zero or a non-integer element, we return None in the list comprehension.

related categories

gistlibby LogSnag