Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to throw an exception as the output of a list comprehension?

I want to throw an exception if an item in a list isn’t an integer through a list comprehension, how would this be done outside of an extra function?

Basically, is there a one-line approach to have an exception be called by the output of a list comprehension?

[raise Exception('Incorrect Data Type Present') for x in my_list if not isinstance(x,int)]

This, understandably, does not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you want is a simple if statement, not a list comprehension.

if not all(isinstance(x, int) for x in my_list):
    raise Exception('Incorrect Data Type Present')

or equivalently,

if any(not isinstance(x, int) for x in my_list):
    raise Exception('Incorrect Data Type Present')

Based on the message, Exception should probably be TypeError.

You could also use a for loop in place of the generator expression consumed by all/any:

for x in my_list:
    if not isinstance(x, int):
        raise Exception('Incorrect Data Type Present')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading