Python filter none from list | Example code

With Python, the filter function can check for any None value in the list and remove them and form a filtered list without the None values.

Python filter(None) from list example code

Simple example code.

list1 = [10, None, 30, None, None, 60, 70, None]

res = list(filter(None, list1))

print(res)

Output:

Python filter none from list

Remove None value from a list without removing the 0 value

A list comprehension is likely the cleanest way:

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

res = [x for x in L if x is not None]

print(res)

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]
res = list(filter(partial(is_not, None), L))

print(res)

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

Do comment if you have any doubts and suggestions on this Python filter None code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.