python

Python code to remove falsy values(None, False, [], {}, etc)

Removing falsy values from the python list can be easily done using the filter method. There are more ways to remove falsy values from the python list. We are listing them here one by one.

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_1list_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_resulteg_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)
We can also use for loop to remove falsy values from the python list. Just check if item return true from bool(item) in each iteration. If it returns true we put it in the final list.
Was this helpful?