filter() Function in Python

Python filter() Function

The filter() function in Python is a built-in function that allows you to create a new iterable by filtering out elements from an existing iterable based on a given condition. It takes in two arguments: a function that defines the condition and an iterable object.

The syntax for using filter() is as follows:

filter(function, iterable)

The function parameter is a function that takes in a single argument and returns a Boolean value (True or False). This function is applied to each element in the iterable, and only the elements for which the function returns True are included in the resulting iterable.

Here's an example to illustrate how filter() works. Let's say we have a list of numbers and we want to filter out only the even numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def is_even(n):
    return n % 2 == 0

even_numbers = filter(is_even, numbers)

print(list(even_numbers))

Output:

[2, 4, 6, 8, 10]

In this example, the is_even() function is used as the condition. It takes an argument n and checks if it is divisible by 2 (i.e., if the remainder is 0). The filter() function applies this condition to each element in the numbers list and returns a new iterable containing only the even numbers. Finally, we convert the iterable to a list and print the result.

Note that filter() returns an iterable, so if you want to see the filtered elements, you need to convert it to a list or iterate over it in some way.

It's also important to mention that in Python 3, filter() returns a filter object. If you specifically need a list as the output, you can convert the filter object to a list using the list() function, as shown in the example.