Skip to content

How to remove None in Python | Example code

  • by

Use the 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 the iterate method but with a sorter code. Just check for True values and filter without the 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 or suggestions on this Python None topic.

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

Your email address will not be published. Required fields are marked *

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