๐ Day 97/150 – filter() Function in Python
The filter() function is a built-in Python function used to select elements from an iterable based on a condition. It returns only those elements for which the given function evaluates to True.
Syntax:
filter(function, iterable)In this post, we'll explore four common examples of using the filter() function in Python.
Method 1 – Using filter() with a Normal Function
Filter even numbers from a list using a normal function.
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
result = list(filter(is_even, numbers))
print(result)
Output
[2, 4, 6]Explanation
is_even() returns True if a number is even.
filter() applies this function to every element in the list.
Only the elements for which the function returns True are kept.
list() converts the filter object into a list.
Method 2 – Using filter() with a Lambda Function
Use a lambda function to write the filtering logic in a single line.
numbers = [10, 15, 20, 25, 30] result = list(filter(lambda x: x > 20, numbers)) print(result)
Output
[25, 30]
Explanation
lambda x: x > 20 checks whether each number is greater than 20.
filter() keeps only the numbers that satisfy the condition.
The result is converted into a list.
Method 3 – Filtering Strings
Filter words whose length is greater than 5.
Output
Explanation
len(word) > 5 checks the length of each word.
filter() keeps only the words with more than 5 characters.
This method is useful when working with text data.
Method 4 – Taking User Input
Filter even numbers entered by the user.
10 15 20 25 30numbers = list(map(int, input("Enter numbers separated by spaces: ").split())) result = list(filter(lambda x: x % 2 == 0, numbers)) print("Even numbers:", result)
Sample Input
Output
Even numbers: [10, 20, 30]Explanation
input() reads the numbers as a string.
split() separates them into a list.
map(int, ...) converts each value to an integer.
filter() selects only the even numbers.
Comparison of Methods
| Method | Best For |
|---|---|
| Normal Function | Reusable filtering logic |
| Lambda Function | Short and simple conditions |
| String Filtering | Filtering text data |
| User Input | Interactive programs |
๐ฅ Key Takeaways
filter() selects elements that satisfy a condition.
It returns a filter object, which is usually converted to a list using list().
filter() works with both normal functions and lambda functions.
It is commonly used to filter numbers, strings, and other collections.
filter() makes code shorter and more readable than writing equivalent loops.
Stay tuned for Day 98 of the #150DaysOfPython series! ๐
%20Function%20in%20Python.png)

