Tuesday 21 September 2021

Python: remove None values from a list

Python do not have null values, instead it has None. None is equivalent to null in other languages, and it is not the same as an empty string, False, or a zero.

 

In this post, I am going to explain how to delete None values from a list. Using filter function, we can filter the None values from a list.

 

remove_none_from_list.py

data = [2, None, 3, '', True, False, 0]

def is_not_none(element):
    if element is None :
        return False
    return True

data_without_none = list(filter(is_not_none,data))

print('data -> ', data)
print('data_without_none -> ', data_without_none)

 

Output

data ->  [2, None, 3, '', True, False, 0]
data_without_none ->  [2, 3, '', True, False, 0]

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment