l=[None,None]
is there a function that checks whether list l contains only None or not?
Try any() - it checks if there is a single element in the list which is considered True in a boolean context. None evaluates to False in a boolean context, so any(l) becomes False . Note that, to check if a list (and not its contents) is really None , if l is None must be used.
Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).
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.
In this case, they are the same. None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.
If you mean, to check if the list l
contains only None,
if all(x is None for x in l):
...
L == [None] * len(L)
is much faster than using all() when L is all None
$ python -m timeit -s'L=[None]*1000' 'all(x is None for x in L)'
1000 loops, best of 3: 276 usec per loop
$ python -m timeit -s'L=[None]*1000' 'L==[None]*len(L)'
10000 loops, best of 3: 34.2 usec per loop
Try any()
- it checks if there is a single element in the list which is considered True
in a boolean context. None
evaluates to False
in a boolean context, so any(l)
becomes False
.
Note that, to check if a list (and not its contents) is really None
, if l is None
must be used. And if not l
to check if it is either None (or anything else that is considered False
) or empty.
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