The Boolean Any And All Operators in Python are Great for Input Validation
1 min readAug 7, 2021
The aim of this pageđź“ťis to describe any
and all
boolean operators in python and a single simple use case: input validation, particularly if part of an input can be found in any of the list items (e.g. folder names).
any
andall
are equivalent to the logical operatorsand
andor
- they are specifically used for iterable series of [bool] values.
any
takes an iterable and tells you if any elements in it are true.all
takes an iterable and tells you if all the elements in it are true.
- this is amazing for validation of input
- my case is checking if a list of strings contains a substring which is an ID
- only if the ID has not been used yet, I proceed with the function, else I raise a ValueError
- if the first 2 characters of a selected name are found in the
sectionFolders
list offolder
s, it is over
if any([name[:2] in folder for folder in sectionFolders]):
raise ValueError(
f"ID already used, select a proper one"
)