Home Ask Login Register

Developers Planet

Your answer is one click away!

Michael Gruenstaeudl February 2016

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.

Answers


dhke February 2016

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.


B. M. February 2016

You can keep lazy evaluation and enhance lisibility by :

for lst in lst_of_lsts :
   if target_string not in lst : 
      raise ValueError('At least one  list does not contain "%s"' % (target_string))

Post Status

Asked in February 2016
Viewed 2,945 times
Voted 12
Answered 2 times

Search




Leave an answer


Quote of the day: live life