In this tutorial, we will learn about how to remove null values from a list in Python with a coding example. In many situations, you might have to come up with this type of requirements.
I know you are here just because you are in need of this trick to remove null values from a list that means if user enter large amount of input where have any null value then by this code null/none values are removed.
Suppose we have a large dataset, and on analyzing it we find missing values or no values. To ensure that data is clean, such null values must be removed from dataset. Null values affect the performance and accuracy of the model, so it is necessary to remove unwanted null values from the data before processing to make it effective.
If you don’t know how to remove null values from a list using Filter() Method, then you are at the right place. Because in this tutorial we will understand how remove null values from a list using Python. And this method choose to save time and hustle.
Remove null values from a list in Python
Let’s learn this with a easy coding example,
1. At first, Function Definition –
def get_user_list(prompt):
def get_user_list(prompt):
defines a function namedget_user_list
that takes a single parameter,prompt
, which is a string used to ask the user for input.
2. Then Prompt User Input –
input_string = input(prompt)
- Displays the prompt message to the user and captures the input as a string in
input_string
.
3. Then Process the Input –
return [item.strip() for item in input_string.replace(',', ' ').split()]
input_string.replace(',', ' ')
:- Replaces any commas in the input string with spaces. This allows handling of lists separated by both spaces and commas.
input_string.split()
:- Splits the modified string into a list of substrings based on spaces. For example, if the input is
"a, b, c"
, this will be split into["a", "b", "c"]
.
- Splits the modified string into a list of substrings based on spaces. For example, if the input is
[item.strip() for item in input_string.split()]
:- A list comprehension that iterates over each substring.
item.strip()
removes any leading or trailing whitespace from each substring.- This results in a list of clean strings, free from extra spaces.
4. After that, Get User Input –
user_list = get_user_list("Enter the elements of the list separated by spaces or commas: ")
Call the Function:
get_user_list
is called with the prompt"Enter the elements of the list separated by spaces or commas: "
.- The user enters a series of items separated by spaces or commas.
- The function processes the input and returns a list of cleaned strings, which is assigned to
user_list
.
5. Then Print the Original List –
print("Original list:", user_list)
Display the List:
- This line prints the original list of strings that the user has entered. It shows the raw list before any filtering.
6. Next Remove Empty Strings –
filtered_list = list(filter(None, user_list))
Filter Empty Strings:
filter(None, user_list)
:filter()
is used to remove elements from the list that are considered falsy. In this case, an empty string (''
) is considered falsy.- The
None
argument infilter()
means that the filtering is based on the truthiness of each item. Any item that evaluates toFalse
(like an empty string) is excluded.
list()
converts the filter object into a list.
7. Finally, Print the Filtered List –
print("Filtered list:", filtered_list)
Display the Filtered List:
- This line prints the filtered list, which has had all empty strings removed. It shows only the non-empty items from the original list.
Python Code – “Remove null values from a list”
# Function to get a list from user input def get_user_list(prompt): # Prompt the user for input input_string = input(prompt) # Convert the input string into a list of strings # Split the input string by spaces or commas # Strip leading/trailing whitespace from each item return [item.strip() for item in input_string.replace(',', ' ').split()] # Get a list from the user user_list = get_user_list("Enter the elements of the list separated by spaces or commas: ") # Print the original list print("Original list:", user_list) # Remove empty strings using filter() filtered_list = list(filter(None, user_list)) # Print the filtered list print("Filtered list:", filtered_list)
Let’s take an Input,
If the user enter – apple banana ,, mango
Then the Output :
Enter the elements of the list separated by spaces or commas: apple banana ,, mango Original list: ['apple', 'banana', ',', 'mango'] Filtered list: ['apple', 'banana', 'mango']
Here’s a summary :
- Purpose: The code takes a string input from the user, splits it into a list of elements based on spaces or commas, and then filters out any empty strings.
- Process:
- Input Handling: The user enters a string with items separated by spaces or commas.
- List Conversion: The string is converted into a list of items, with any leading or trailing whitespace removed from each item.
- Filtering: Any empty elements that might result from extra spaces or commas are removed.
- Output: The original and filtered lists are printed.
This code effectively cleans up a user’s input to produce a well-structured list of items.
You may also learn,