filter() in Python
filter() in Python
The filter() function in Python is used to filter elements from an iterable (such as a list, tuple, or other iterable objects) based on a specified condition. It returns an iterator containing the elements that satisfy the given condition.
Python filter()
Python is a versatile programming language known for its rich set of functions and libraries. One of the essential functions in Python is `filter()`. At its core, `filter()` is a built-in Python function that allows you to filter elements from an iterable (e.g., lists, tuples, or sets) based on a given condition. It returns an iterator containing only the elements that satisfy the specified criteria.
Syntax
filter(function, iterable)
- function: A function that defines the filtering condition.
- iterable: The iterable (e.g., a list) that you want to filter.
Code 1:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def is_even(x): return x % 2 == 0 even_numbers = filter(is_even, numbers) # Convert the result to a list or another iterable to see the filtered elements even_numbers_list = list(even_numbers) print(even_numbers_list)
Output :
[2, 4, 6, 8, 10]
In the above code, the is_even function is used as the condition, and filter() returns an iterator containing only the even numbers from the numbers list.
Applications of filter()
There are numerous uses for the Python filter() function. In terms of memory usage and processing speed, it is the ideal replacement for list comprehension. To separate or filter elements based on the function check, the filter function can be used in conjunction with lambda functions. In reality, you can also use a regular/traditional function in instead of a lambda function. You can use lambda functions for simple filtering conditions without defining a separate function.
You can use the filter function, for instance, to separate the odd and even components of a list of numbers into two independent sets. It can even be used to select out dictionaries based on their keys from a list of dictionaries.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment