I'm trying to do a simple test that returns True
if any of the results of a list are None
. However, I want 0
and ''
to not cause a return of True
.
list_1 = [0, 1, None, 4] list_2 = [0, 1, 3, 4] any(list_1) is None >>>False any(list_2) is None >>>False
As you can see, the any()
function as it is isn't being helpful in this context.
Use the in operator to check if any item in a list is None, e.g. if None in my_list: . The in operator tests for membership. For example, x in l evaluates to True if x is a member of l , otherwise it evaluates to False .
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.
For list
objects can simply use a membership test:
None in list_1
Like any()
, the membership test on a list
will scan all elements but short-circuit by returning as soon as a match is found.
any()
returns True
or False
, never None
, so your any(list_1) is None
test is certainly not going anywhere. You'd have to pass in a generator expression for any()
to iterate over, instead:
any(elem is None for elem in list_1)
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