remove None value from a list without removing the 0 value
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]
Just for fun, here's how you can adapt filter
to do this without using a lambda
, (I wouldn't recommend this code - it's just for scientific purposes)
>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(partial(is_not, None), L)
[0, 23, 234, 89, 0, 35, 9]
A list comprehension is likely the cleanest way:
>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]
There is also a functional programming approach but it is more involved:
>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]
Using list comprehension this can be done as follows:
l = [i for i in my_list if i is not None]
The value of l is:
[0, 23, 234, 89, 0, 35, 9]
@jamylak answer is quite nice, however if you don't want to import a couple of modules just to do this simple task, write your own lambda
in-place:
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(lambda v: v is not None, L)
[0, 23, 234, 89, 0, 35, 9]
For Python 2.7 (See Raymond's answer, for Python 3 equivalent):
Wanting to know whether something "is not None" is so common in python (and other OO languages), that in my Common.py (which I import to each module with "from Common import *"), I include these lines:
def exists(it):
return (it is not None)
Then to remove None elements from a list, simply do:
filter(exists, L)
I find this easier to read, than the corresponding list comprehension (which Raymond shows, as his Python 2 version).