Imagine we have a bunch of things, like a list of numbers, a collection of fruits, or any other group of items. Now, let's say we want to pick out only certain items from that group based on a specific condition. This is where the filter function comes in handy.
Let's say we have a list of numbers, and we want to filter out only the even numbers. We define a condition-checking function that checks if a number is even. Then, we pass this function and the list of numbers to the filter function. It goes through each number, applies the condition-checking function, and keeps only the numbers that are even. Finally, it gives us a new list containing only the even numbers.
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = list(filter(is_even, numbers))
print(filtered_numbers)
Output
[2, 4, 6, 8, 10]
We can also utilize lambda expressions to define filtering conditions directly within the filter function.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(filtered_numbers)
We will get the same output as earlier.
[2, 4, 6, 8, 10]
Similarly, we can use the filter function with dictionaries or other iterable objects. Just provide a condition-checking function that examines each item and decide whether to keep it or discard it.
By using the filter function, we can easily sort through your data and get a new set of items that meet our specific criteria. It saves you time and makes our code more readable and efficient.
No comments:
Post a Comment