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.
CodePudding user response:
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')