Home  >  Article  >  Backend Development  >  How to remove null values ​​from a list in Python

How to remove null values ​​from a list in Python

PHPz
PHPzforward
2024-03-02 08:56:02721browse

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!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete