remove None value from a list without removing the 0 value


Question

This was my source I started with.

My List

L = [0, 23, 234, 89, None, 0, 35, 9]

When I run this :

L = filter(None, L)

I get this results

[23, 234, 89, 35, 9]

But this is not what I need, what I really need is :

[0, 23, 234, 89, 0, 35, 9]

Because I'm calculating percentile of the data and the 0 make a lot of difference.

How to remove the None value from a list without removing 0 value?

1
216
3/1/2017 12:33:45 PM

Accepted Answer

>>> 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]
307
4/19/2013 3:42:17 AM

FWIW, Python 3 makes this problem easy:

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(None.__ne__, L))
[0, 23, 234, 89, 0, 35, 9]

In Python 2, you would use a list comprehension instead:

>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon