Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check whether list contains only None in python

Tags:

python

l=[None,None]

is there a function that checks whether list l contains only None or not?

like image 992
goblin2986 Avatar asked Aug 27 '10 11:08

goblin2986


People also ask

How do you know if a list contains only none?

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.

How do you know if a list is not none in Python?

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).

How do I check if a list Isempty?

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.

Is none and == None 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.


3 Answers

If you mean, to check if the list l contains only None,

if all(x is None for x in l):
  ...
like image 50
kennytm Avatar answered Oct 19 '22 09:10

kennytm


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
like image 33
John La Rooy Avatar answered Oct 19 '22 11:10

John La Rooy


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.

like image 17
Alexander Gessler Avatar answered Oct 19 '22 10:10

Alexander Gessler