← Back to Articles
Tutorial

Understanding Python's filter() Function

Learn how to use Python's filter() function with examples and tips.

The Python filter() function is a powerful built-in function used to filter elements of an iterable. By applying a function to each element, it returns an iterator yielding those items for which the function returns true. This is particularly useful for cleaning datasets or extracting information that meets specific criteria.

To use the filter() function, you provide two arguments: a function and an iterable. The function should return a boolean value. For example, you can filter out odd numbers from a list by using a lambda function. Here's a basic usage: filter(lambda x: x % 2 == 0, numbers). This will return an iterator of even numbers.

When using the filter() function, ensure that the function provided is efficient and correctly handles the data types of the iterable. It's also a good practice to convert the resulting iterator into a list or another suitable collection type for further processing or inspection.

One common mistake is forgetting that filter() returns an iterator, not a list. If you try to access the elements directly without conversion, you may encounter unexpected behavior. Always remember to convert the iterator to a list or similar structure to view the filtered results.

Code Examples

Filter Even Numbers

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4, 6]

Filter Words by Length

words = ['apple', 'banana', 'pear', 'kiwi']
short_words = list(filter(lambda x: len(x) < 5, words))
print(short_words)  # Output: ['pear', 'kiwi']

More Python Tutorials