Zone Of Makos

Menu icon

Filter in Python

The filter() function in Python is a built-in function that allows you to filter elements from an iterable (list, tuple, dictionary, etc.) based on a condition. It returns a new iterable containing only the elements that meet the condition. The filter() function takes two arguments: a function that defines the condition and an iterable to filter. In this lesson, we'll explore how to use the filter() function in Python and how it can help you manipulate data more efficiently.

Syntax

The syntax of the filter() function is as follows:


filter(function, iterable)

The first argument, function , is a function that takes one argument and returns a Boolean value. This function defines the condition to filter the iterable. The second argument, iterable , is the iterable that you want to filter.

Examples

Here are some examples of how to use the filter() function in Python:


# Example 1: Filter even numbers from a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

result = list(filter(lambda x: x % 2 == 0, my_list))
print(result) # Output: [2, 4, 6, 8, 10]

# Example 2: Filter students with a grade greater than 70
students = {
    "John": 85,
    "Jane": 70,
    "Bob": 92,
    "Alice": 65
}

result = dict(filter(lambda item: item[1] > 70, students.items()))
print(result) # Output: {"John": 85, "Bob": 92}

Conclusion

The filter() function is a powerful tool in Python that allows you to filter elements from an iterable based on a condition. It takes a function that defines the condition and an iterable to filter, and returns a new iterable containing only the elements that meet the condition. The filter() function is an essential part of data manipulation in Python, and it can help you write more concise and efficient code.