Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising error if string not in one or more lists

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.

like image 976
Michael G Avatar asked Jan 07 '23 16:01

Michael G


1 Answers

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.

like image 187
dhke Avatar answered Jan 15 '23 18:01

dhke