I am fairly new to Python, and I was wondering if there was a succinct way of testing a value to see if it is one of the values in the list, similar to a SQL WHERE clause. Sorry if this is a basic question.
MsUpdate.UpdateClassificationTitle in (
'Critical Updates',
'Feature Packs',
'Security Updates',
'Tools',
'Update Rollups',
'Updates',
)
i.e, I want to write:
if MsUpdate.UpdateClassificationTitle in (
'Critical Updates',
'Feature Packs',
'Security Updates',
'Tools',
'Update Rollups',
'Updates'
):
then_do_something()
We can use the in-built python List method, count(), to check if the passed element exists in the List.
To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.
The keys() function and the "in" operator can be used to see if a key exists in a dictionary. The keys() method returns a list of keys in the dictionary, and the "if, in" statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False.
“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.
Seems succinct enough, but if you're using it more than once you should name the tuple:
titles = ('Critical Updates',
'Feature Packs',
'Security Updates',
'Tools',
'Update Rollups',
'Updates')
if MsUpdate.UpdateClassificationTitle in titles:
do_something_with_update(MsUpdate)
Tuples use parenthesis. If you want a list change it to square brackets. Or use a set, which has faster lookups.
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