I wish to raise an error manually if a target_string does not occur in one or more lists of a list of lists.
if False in [False for lst in lst_of_lsts if target_string not in lst]:
raise ValueError('One or more lists does not contain "%s"' % (target_string))
Surely there is a more Pythonic solution than the one specified above.
Use all()
if not all(target_string in lst for lst in lst_of_lsts):
raise ValueError('One or more lists does not contain "%s"' % (target_string))
The generator yields True
or False
for each individual test and all()
checks if all of them are true. Since we are using a generator, the evaluation is lazy, i.e. it stops when the first False
is found without evaluating the full list.
Or if the double in
on the same label seems confusing, one might
if not all((target_string in lst) for lst in lst_of_lsts):
raise ValueError('One or more lists does not contain "%s"' % (target_string))
but I'm not so sure any more that actually increases readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With