Remove None values from list without removing 0 value - Python

Last Updated : 08 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Removing None values from a list in Python means filtering out the None elements while keeping valid entries like 0. For example, given the list [1, None, 3, 0, None, 5], removing only None values results in [1, 3, 0, 5], where 0 is retained as a valid element. Let's explore various methods to achieve this efficiently.

Using List Comprehension

List comprehension is a concise way to filter out None values from a list. It creates a new list, iterating over the original list and adding only those elements that are not None.

Python
a = [1, None, 3, None, 5, 0]

b = [x for x in a if x is not None]
print(b)

Output
[1, 3, 5, 0]

Explanation: List comprehension iterates through each element of a. It checks if the element is not None and only those elements are added to the new list b.

Using filter()

filter() function allows us to remove None values by applying a condition to each element of the list. It creates a new list containing only the elements that meet the specified condition.

Python
a = [1, None, 3, 0, None, 5]

b = list(filter(lambda x: x is not None, a)) 
print(b)

Output
[1, 3, 5]

Explanation: filter() function takes a lambda that filters out elements that are None. The result is converted back into a list using list().

Using itertools.filterfalse()

itertools.filterfalse() function offers an alternative to filter(). It filters out None values by applying an inverted condition i.e., it keeps elements that are not None .

Python
import itertools
a = [1, None, 3, None, 0 , 5]

b = list(itertools.filterfalse(lambda x: x is None, a))
print(b)

Output
[1, 3, 0, 5]

Explanation: itertools.filterfalse(), which returns an iterator that filters out None values by checking if the element is None. The result is converted to a list.

Using del keyword

del keyword directly removes elements from the list in place. This method is less efficient than the others because it modifies the list during iteration, which can lead to skipping elements or unnecessary re-indexing.

Python
a = [1, None, 3, 0, None, 5]
i = 0 # counter variable

while i < len(a):
    if a[i] is None:
        del a[i]
    else:
        i += 1
print(a)

Output
[1, 3, 0, 5]

Explanation: while loop checks each element for None and removes it using del. The index i increments only when the element is not None to avoid skipping elements after deletion.


Practice Tags :

Similar Reads