Reputation: 1009
l=[None,None]
is there a function that checks whether list l contains only None or not?
Upvotes: 40
Views: 41611
Reputation: 8103
I personally prefer making a set
and then verifying if it is equal to a set with one element None
:
set(l) == {None}
assert set([None, None, None]) == {None}
assert set([None, 2, None]) != {None}
Not the fastest but still faster than the all(...)
implementation:
$ python -m timeit -s'L=[None]*1000' 'all(x is None for x in L)'
10000 loops, best of 3: 59 usec per loop
$ python -m timeit -s'L=[None]*1000' 'set(L)=={None}'
100000 loops, best of 3: 17.7 usec per loop
$ python -m timeit -s'L=[None]*1000' 'L==[None]*len(L)'
100000 loops, best of 3: 7.17 usec per loop
Upvotes: 6
Reputation: 304205
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
Upvotes: 36
Reputation: 1342
If you want to check if the members of the list are None, then you can loop over the items and check if they are None
If you want to check if list itself is None, you can use type(varlist) and it will return None
you can do
if (lst == None): ... print "yes"
works.
Upvotes: 0
Reputation: 523314
If you mean, to check if the list l
contains only None,
if all(x is None for x in l):
...
Upvotes: 51
Reputation: 46607
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.
Upvotes: 17