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:
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.