To remove all instances of None from a list using Python, the easiest way is to use list comprehension.
lst = [1,2,3,4,None,2,1,None,3,2]
list_without_none = [x for x in lst if x != None]
print(list_without_none)
#Output:
[1, 2, 3, 4, 2, 1, 3, 2]
You can also use the Python filter() function.
lst = [1,2,3,4,None,2,1,None,3,2]
list_without_none = list(filter(lambda x: x != None, lst))
print(list_without_1)
#Output:
[1, 2, 3, 4, 2, 1, 3, 2]
When working with lists in Python, it can be valuable to be able to easily filter and remove unwanted values from your list.
One such situation where you may want to remove all instances of None from a list.
We can easily remove all instances of None from a list of a value using Python with list comprehension. List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Below is the code which will allow you to remove all None values from a list using list comprehension in Python.
lst = [1,2,3,4,None,2,1,None,3,2]
list_without_none = [x for x in lst if x != None]
print(list_without_none)
#Output:
[1, 2, 3, 4, 2, 1, 3, 2]
Removing All Instances of None from List with Python filter() Function
The Python filter() function is a built-in function that allows you to process an iterable and extract items that satisfy a given condition.
We can use the Python filter() function to extract all the items in a list of numbers which do not equal the value you want to get rid of and remove all instances from a list.
Below is some example code showing you how to remove all occurrences of None from a list using the filter() function.
lst = [1,2,3,4,None,2,1,None,3,2]
list_without_none = list(filter(lambda x: x != None, lst))
print(list_without_1)
#Output:
[1, 2, 3, 4, 2, 1, 3, 2]
Removing All Instances of Any Value from List Using Python
Above, you’ve seen a few example of how to remove all occurrences of None from a list in Python.
The solutions from above apply to removing all instances of any value from a list as well.
For example, if we instead wanted to remove all zeros from a list, we could do that easily with list comprehension in Python by adjusting the code above.
list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0]
list_without_zeros = [x for x in list_of_numbers if x != 0]
print(list_without_zeros)
#Output:
[1,4,2,-4,3,-1]
Another example would be if we have a list of numbers with a lot of NaN values.
Below is an example of how you can remove NaN from a list in Python.
from math import nan, isnan
list_with_nan= [0, 1, 3, nan, nan, 4, 9, nan]
list_without_nan = [x for x in list_with_nan if isnan(x) == False]
print(list_without_nan)
#Output:
[0, 1, 3, 4, 9]
Hopefully this article has been useful for you to learn how to remove all instances of None from a list in Python.