One of the most attractive features of Python is its readability and conciseness, allowing developers to write elegant and efficient code. In this article, we will explore a Python method called “Compact” that helps remove falsy values from a list using filter().
The Compact method is a simple yet powerful Python function that removes falsy values (False, None, 0, and “”) from a list. It does this by utilizing the filter() function, which returns an iterator that includes only the elements of the list that satisfy a specific condition.
Here is the code for the Compact method:
def compact(lst):
return list(filter(None, lst))
As we can see, the Compact method takes a list as an argument and returns a new list with all falsy values removed. The filter() function is used to iterate over the elements of the list and remove any elements that are False, None, 0, or “”.
Example Usage of the Compact Method
To illustrate the usage of the Compact method, let’s consider an example. Suppose we have a list of numbers and strings that includes falsy values:
lst = [0, 1, False, 2, '', 3, 'a', 's', 34]
We can use the Compact method to remove all falsy values from the list and return a new list with only the truthy values:
result = compact(lst)
print(result) # [1, 2, 3, 'a', 's', 34]
As we can see, the Compact method has removed all falsy values from the list and returned a new list with only the truthy values.
That’s it.
I hope you find this useful.