In Python, there are three global functions that can be quite useful when working with collections: map()
, filter()
, and reduce()
. In this blog post, we will focus on how to use the filter()
function.
Note: In some cases, using list comprehensions can be a more intuitive and Pythonic approach.
The filter()
function takes an iterable as input and returns a filter object, which is another iterable that contains only the items that pass a given filtering condition.
To filter items using the filter()
function, you need to provide a filtering function that determines whether an item should be included in the filtered result. This function should return True
or False
based on the filtering condition.
Here is an example that demonstrates how to use the filter()
function:
numbers = [1, 2, 3]
def isEven(n):
return n % 2 == 0
result = filter(isEven, numbers)
print(list(result)) # Output: [2]
In this example, the isEven()
function is used as the filtering function. It checks whether a number is even or not by checking if the remainder of the number divided by 2 is equal to 0. The filter()
function then applies this filtering function to each item in the numbers
list and returns a filter object that only contains the items that satisfy the filtering condition. Finally, the filter object is converted to a list using the list()
function and printed.
Alternatively, you can use a lambda function to make the code more concise:
numbers = [1, 2, 3]
result = filter(lambda n: n % 2 == 0, numbers)
print(list(result)) # Output: [2]
In this case, the filtering condition is specified directly within the lambda function, making the code shorter and more compact.
Using the filter()
function can be a convenient way to extract specific items from a collection that satisfy certain conditions. It is especially useful when working with large datasets or when you need to perform complex filtering operations.
Overall, understanding how to use the filter()
function in Python can greatly enhance your ability to work with collections efficiently and effectively.