Home >Backend Development >Python Tutorial >How to remove None value from list in Python
In Python we can use a for loop to traverse and filter None values, or use the filter() function to delete None values and then return a new list without None values. Below we will introduce the deletion method, I hope it will be helpful to everyone.
What is the value of None?
In Python there is a value called None, which means there is no value. None is the only value of the NoneType data type. Like the Boolean values True and False, None must have a capital N.
How to remove None value from list?
Method 1: Use a for loop to traverse and filter the None value
We can traverse the entire list and filter all The non-None value is appended to the new list, for example:
test_list = [1, None, 4, None, None, 5, 8, None] # 输出原始列表 print(str(test_list)); #删除列表中的None值 res = [] for val in test_list: if val != None : res.append(val); # 输出新的列表 print (str(res))
Output:
Method 2 : Use the filter() function
The filter() function is used to filter the sequence, filter out elements that do not meet the conditions, and return a new list composed of elements that meet the conditions. It checks the list for any None values and removes them and forms a filtered list without None values.
test_list = [1, None, 4, None, None, 5, 8, None] # 输出原始列表 print(str(test_list)); #使用filter()函数,删除列表中的None值 res = list(filter(None, test_list)) # 输出新的列表 print (str(res ))
Output:
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to remove None value from list in Python. For more information, please follow other related articles on the PHP Chinese website!