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

PHPz
Release: 2024-03-02 08:56:02
forward
736 people have browsed it

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)
Copy after login

Output result:

[1, 2, 3, 4, 5]
Copy after login
Copy after login

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)
Copy after login

Output result:

[1, 2, 3, 4, 5]
Copy after login
Copy after login

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!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template