Home > database >  how to check non-empty selection?
how to check non-empty selection?

Time:06-25

I am using plotly-dash dropdown menu with multiple selection enabled. so the dropdown menu returned either an empty list when no selection, or a string ( with one selection) or list of strings ( with multiple selection).

How do I check if returned is not empty?

if I use below, it doesn't work for empty list


if selection is not None:

Thanks for your help.

CodePudding user response:

I think this should work:

def check_selection(selection):
    if selection:
        if isinstance(selection, list):
            return "Multiple Selections"
        else:
            return "One Selection"
    else:
        return "No Selection"

Empty sequences (like strings and lists) are considered "falsy" in Python, and evaluate to the boolean False. Please let me know if I interpreted your question correctly, and this answer helps.

CodePudding user response:

Empty list is not same as None. You can check length of the list using len() function. If length is 0, the list is empty.

Try it:

if len(selection) == 0:
    #code if the list is empty
else:
    #code if list is not empty

The code will also work for string, because as per question if single selection is made, the menu will return a string(which will have some length). We can check in else part of the code as if it is a string or list using type() function.

rlist = [1, 2, 3]
rstring = 'test'
def test_selection(obj):
    if len(obj) == 0:
        print('empty')
    else:
        if type(obj) is str:
            print('str object')
        else:
            print('list')

test_selection(rlist) #output :- list
test_selection(rstring) #output :-  str object
test_selection([])  #output :-  empty
  • Related