Home >Backend Development >Python Tutorial >How to remove null values from a list in Python
To remove null values in the list, you can use list comprehensions or the filter() function.
Method 1: Use list comprehensions You can use list comprehensions to create a new list while filtering out null values in the list.
original_list = [1, 2, None, 3, '', 4, ' ', 5] new_list = [x for x in original_list if x is not None and x != ''] print(new_list)
Output result:
[1, 2, 3, 4, 5]
Method 2: Use filter() function You can use the filter() function to filter out null values in the list and convert the returned results into a list.
original_list = [1, 2, None, 3, '', 4, ' ', 5] new_list = list(filter(lambda x: x is not None and x != '', original_list)) print(new_list)
Output result:
[1, 2, 3, 4, 5]
No matter which method is used, the null values in the list can be filtered out and a new list can be obtained.
The above is the detailed content of How to remove null values from a list in Python. For more information, please follow other related articles on the PHP Chinese website!