How to remove None in Python | Example code

Use filter() function to remove None from a list in Python. Other ways are the Naive Method and list comprehension.

Example remove None in Python

Simple example code deletes/drops none from the list in Python.

Using filter() function

This method checks for any None value in the list and removes them.

list1 = [1, None, 3, None, None, 6, 7, None]

res = list(filter(None, list1))

print(res)

Output:

How to remove None in Python

Naive Method iteration

Simply iterate through the whole list and append non-None values into a new list.

list1 = [1, None, 3, None, None, 6, 7, None]

res = []
for val in list1:
    if val is not None:
        res.append(val)

print(res)

Output: [1, 3, 6, 7]

Using list comprehension

Same as iterate method but sorter code. Just check for True values and filter without None value list.

list1 = ["A", None, 3, None, None, 6, 7, None]

res = [i for i in list1 if i]

print(res)

Output: [‘A’, 3, 6, 7]

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

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.