Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check variable if it is in a list

Tags:

python

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()
like image 305
EdgeCase Avatar asked Oct 10 '11 13:10

EdgeCase


People also ask

How do you see if a variable is in a list Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List.

How do I check if a variable is a list or a string?

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.

How do you check if a key is in a list?

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.

How do you check if a value isn't in a list?

“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.


1 Answers

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.

like image 75
Steven Rumbalski Avatar answered Oct 30 '22 03:10

Steven Rumbalski