Python Program to Remove Null Values from a List
If you’re working with Python, you might at one point need to remove null values from a list. In programming, null values are defined as the absence of any value, and while null values can be necessary, there are times when they need to be removed from lists to prevent errors or unintended behavior. Fortunately, Python makes this a straightforward exercise.
In this article, we’ll go over how to remove null values from a list in Python, and we’ll provide some examples to help you understand the process.
Basic Method to Remove Null Values
The quickest and most straightforward method to remove null values in Python is to use a loop. This loop method will go through each element in the list and remove every instance of null.
Here’s an example of this basic method:
# Create a list with null values
list_with_nulls = [None, 2, None, 3, None, 4, None]
# Use a loop to remove all null values
list_without_nulls = [i for i in list_with_nulls if i is not None]
# Print the new list
print(list_without_nulls)
In this example, we first create a list that contains null values. Then, we use a loop to create a new list that contains only the non-null values.
The loop we use, [i for i in list_with_nulls if i is not None]
, is a list comprehension that goes through each element in the original list and builds a new list containing only the values that are not null.
The if i is not None
condition checks if the current element is not null, and if it is, we don’t add it to the new list. Once every iterable item has been iterated through, the new list containing only non-null values is returned.
Alternative Method to Remove Null Values
If you want to remove all null values from a list without using a loop method, you can use the filter()
function. This method filters out any null values when applied to the original list.
Here’s an example:
# Create a list with null values
list_with_nulls = [None, 2, None, 3, None, 4, None]
# Use filter function to remove all nulls
list_without_nulls = list(filter(None, list_with_nulls))
# Print the new list
print(list_without_nulls)
In this example, we create a list similar to the previous example. This new list contains null values. After creating that list, we use the filter()
function to create a new list without null values.
The filter()
function takes two arguments: None
, which means that it will use the default filtering behavior; and list_with_nulls
, which is the list we want to apply the filter to. The returned list, list_without_nulls
, contains only the non-null items from the original list.
Conclusion
That’s it! These are the two main methods for removing null values from a list in Python. With just a simple loop comprehension or using the filter()
function you are able to filter out any None
values from your list.