Skip to content

Python filter none from list | Example code

  • by

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 the 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 or suggestions on this Python filter None code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading