Search code examples
pythonlistrecursionnonetype

Testing Nonetype elements in a list


I have this kind of a list inputs = [None, None, None, None, None, None, None, None] I want to evaluat if all elements are the same that is None: if so return an empty list that is []

What I have tried so far doesn't seem to work:

if all(inputs) is None: print([]) else: print("somthing else"


Solution

  • all() tells you if every element in the iterable you pass to it is True. So, all([True, True, True]) would be True, but all([True, False]) wouldn't.

    If you want to see if all elements are None, this is what you need:

    all(x is None for x in inputs)
    

    What this does is use a generator to loop over all the values in inputs, checking if they are None and all() checks all those results and returns True if all of them are True.