Python built-in Method - filter()
The filter()
method is a built-in function in Python that creates an iterator from elements of an iterable for which a given function returns true. In other words, it filters out the elements from an iterable that don't meet a specified condition and returns the remaining elements.
Here is the syntax for filter()
method:
filter(function, iterable)
where function
is a function that takes one argument and returns a Boolean value indicating whether the argument should be included in the output, and iterable
is an iterable object (such as a list or tuple) that contains the elements to be filtered.
Here's an example of how to use filter()
:
def is_even(num): return num % 2 == 0 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = filter(is_even, numbers) print(list(result))
In this example, we define a function is_even()
that takes a number as input and returns True
if the number is even and False
otherwise. We then define a list numbers
containing some integers, and call filter()
with is_even
and numbers
. The resulting iterator is passed to the list()
method, which creates a list from the iterator. The output of the code is [2, 4, 6, 8, 10]
, which contains only the even numbers from the numbers
list.
Note that filter()
returns an iterator, so if you want to get the filtered elements as a list, you need to pass the iterator to the list()
method. Also, you can use a lambda function instead of defining a separate function as the first argument to filter()
. For example, you can replace the is_even()
function in the above code with a lambda function like this:
result = filter(lambda x: x % 2 == 0, numbers)