def sanatize_list(lst):
return list(filter(bool,lst))
list_eg_1 = ["Devsheet", None, "", False]
eg_1_result = sanatize_list(list_eg_1)
print(eg_1_result)
# -> ['Devsheet']
list_eg_2 = [None, "John", False, "Deo"]
eg_2_result = sanatize_list(list_eg_2)
print(eg_2_result)
# -> ['John', 'Deo']
list_eg_3 = [[], "Apple", (), {}]
eg_3_result = sanatize_list(list_eg_3)
print(eg_3_result)
The values that return False are considered as falsy values in Python. Blank list, blank dictionary, blank tuple, False, None, etc. are considered falsy values in python.
In the above code, we have created a python method sanatize_list which will take the list as a parameter and it will return the new list that will not contain any falsy value.
We are using the Python filter() method inside sanatize_list() to filter the falsy values from the list. We have created three lists list_eg_1, list_eg_2, and list_eg_3 that contain falsy values like None, blank list, blank tuple, blank dictionary, etc, and we are passing these lists to the sanatize_list() method and getting results in eg_1_result, eg_2_result, and eg_3_result variables.
def sanatize_list(lst):
result_list = []
for item in lst:
if(bool(item)):
result_list.append(item)
return result_list;
list_eg_1 = ["Devsheet", None, "", False]
eg_1_result = sanatize_list(list_eg_1)
print(eg_1_result)
# -> ['Devsheet']
list_eg_2 = [None, "John", False, "Deo"]
eg_2_result = sanatize_list(list_eg_2)
print(eg_2_result)
# -> ['John', 'Deo']
list_eg_3 = [[], "Apple", (), {}]
eg_3_result = sanatize_list(list_eg_3)
print(eg_3_result)
0 Comments