Introduction: Python filter() Function
When working with Python, there are situations where you need to select only specific items from a collection based on a condition. Whether you’re filtering numbers, strings, or custom objects, manually checking every element can make the code longer and harder to read.
Without a built-in solution, you would need to write loops and conditional statements to create a new collection containing only the required values.
A simple and efficient solution to these situations is the Python filter() Function.
What it is: The filter() function is a built-in Python function that creates an iterator containing only the elements that satisfy a specified condition. It applies a function to each item in an iterable and keeps only those for which the function returns True.
Take a look at a quick example to see how it works.
You can also explore its real-world use cases to learn where it is commonly used.
Now let’s explore its syntax, parameters, return value, and practical examples.
💡 Tip: The filter() function is just one of Python’s built-in functions. Explore the complete Python Built-in Functions Learning Guide to discover more useful functions with practical examples.
Syntax, Parameters, Return Value and Examples: Python filter() Function
The following section explains the syntax, parameters, return value, and a quick example of the Python filter() Function.
Syntax
filter(function, iterable)
Parameters
| Parameter | Description |
|---|---|
function |
A function that returns True or False for each element. If None is provided, only truthy values are kept. |
iterable |
The iterable whose elements need to be filtered, such as a list, tuple, set, or string. |
Return Value
| Return Value | Description |
|---|---|
filter object |
Returns a filter object containing only the elements that satisfy the specified condition. |
Quick Example
The following example filters even numbers from a list.
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))
# Output:
[2, 4, 6]
The filter() function checks each number and keeps only the values that satisfy the given condition. Since the filter object is an iterator, it is converted into a list before printing.
How the Python filter() Function Works
- The
filter()function accepts a function and an iterable. - It applies the function to every element in the iterable.
- Only the elements for which the function returns
Trueare retained. - The filtered values are returned as a filter object.
- The filter object can be converted into a list, tuple, set, or other iterable when needed.
Examples: Python filter() Function
The following examples show how the Python filter() Function works in different programming scenarios.
Example 1: Filtering Even Numbers
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))
# Output:
[2, 4, 6]
Explanation: Every number in the list is tested one by one. Only the even numbers pass the condition, so the final output contains 2, 4, and 6.
Example 2: Filtering Positive Numbers
numbers = [-5, -2, 0, 3, 8, -1]
result = filter(lambda x: x > 0, numbers)
print(list(result))
# Output:
[3, 8]
Explanation: Negative numbers and zero are ignored because they do not satisfy the condition. As a result, only the positive values remain in the filtered output.
Example 3: Filtering Strings by Length
words = ["Pen", "Notebook", "Book", "Python"]
result = filter(lambda word: len(word) > 4, words)
print(list(result))
# Output:
['Notebook', 'Python']
Explanation: Instead of filtering numbers, this example filters strings. Only the words containing more than four characters are retained.
Example 4: Filtering User Input
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
result = filter(lambda x: x % 2 != 0, numbers)
print(list(result))
# Sample Output:
Enter numbers separated by spaces: 4 7 10 15 18
[7, 15]
Explanation: After reading the numbers from the user, filter() selects only the odd values and ignores the even ones.
Example 5: Using None with filter()
values = [0, 5, "", "Python", None, True, False]
result = filter(None, values)
print(list(result))
# Output:
[5, 'Python', True]
Explanation: No custom condition is required in this case. Python automatically removes all falsy values such as 0, an empty string, None, and False, keeping only the truthy ones.
Example 6: Filtering Names That Start with ‘A’
names = ["Alice", "Bob", "Andrew", "David", "Anna"]
result = filter(lambda name: name.startswith("A"), names)
print(list(result))
# Output:
['Alice', 'Andrew', 'Anna']
Explanation: Only the names beginning with the letter "A" satisfy the condition, so the remaining names are excluded from the output.
Use Cases: When to use the filter() Function
Below are some common situations where the Python filter() Function becomes useful:
- Selecting elements that satisfy a specific condition.
- Removing unwanted values from iterables.
- Filtering user input before processing.
- Working with collections of numbers, strings, or objects.
- Cleaning data by removing invalid or empty values.
- Replacing manual filtering loops with cleaner and more readable code.
Key Takeaways: filter() Function
Before wrapping up, here are the key points to remember about the Python filter() Function:
- The
filter()function selects elements that satisfy a specified condition. - It accepts a filtering function and an iterable as arguments.
- It returns a filter object instead of a list.
- The filter object can be converted into a list, tuple, or other iterable when needed.
- Passing
Noneremoves all falsy values from the iterable. - It provides a clean and efficient way to filter data in Python.
In short, the Python filter() Function offers a simple and efficient way to select only the required elements from an iterable, making Python code cleaner, more readable, and easier to maintain.